[Cython] about numpy, c/python namespaces and name clashes, and some tricks ; -)
Robert Bradshaw
robertwb at math.washington.edu
Tue May 13 10:29:34 CEST 2008
On May 12, 2008, at 3:09 PM, Lisandro Dalcin wrote:
> I saw some previous posts complaining about using numpy and some name
> clashes about 'strides', and other stuff like that...
>
> Well, as time pass, I like Cython more and more, because nasty names
> and name clashes can be easyly fixed. For example, lest see some code
> that uses the convention 'cxxxx' for accession at the Cython C-level
> what in python is a 'xxxxx' member (eg. 'cshape' and 'shape'). This is
> so easy for me that I will never mind about requiring the numpy
> headers to change.
>
> Have fun! I post this directly to F.Perez and B. Granger, I will love
> to hear their opinion about this hackery. Any chances to go in for the
> 'official' numpy.pxy, or a variant shipped with numpy ??
> # --------------------------------------------------------------------
>
> cdef extern from "numpy/arrayobject.h":
> int import_numpy "_import_array" () except -1
>
> ctypedef int npy_intp
>
> ctypedef extern class numpy.ndarray [object PyArrayObject]:
> cdef char *cdata "data"
> cdef int cndim "nd"
> cdef int *cshape "dimensions"
> cdef int *cstrides "strides"
> cdef int cflags "flags"
>
> # --------------------------------------------------------------------
>
> import_numpy()
>
> # --------------------------------------------------------------------
>
> def prn(ndarray a):
> cdef int i=0
> # C-level access
> print 'ndim: ', a.cndim
> print 'shape: ', [a.cshape[i] for i from 0 <= i < a.cndim]
> print 'strides: ', [a.cstrides[i] for i from 0 <= i < a.cndim]
> print 'flags: ', a.cflags
> #
> print
> # Python-level access
> print 'ndim: ', a.ndim
> print 'shape: ', a.shape
> print 'strides: ', a.strides
> print 'flags: ', a.flags
>
> # --------------------------------------------------------------------
I am having trouble understanding exactly what you're trying to
accomplish here--what is the correspondence between strides and
cstrides, and how will they be kept in sync? Why not let a.ndim be
the c attribute that gets coerced to a python attribute when needed?
For some types where coercion is not possible (e.g. the int* shape)
then it could transform the above to (<object>a).shape and be
implemented via the property: __get__ mechanism as at http://
www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/version/Doc/Manual/
extension_types.html#Properties (if it exists?). Not having two names
that point to the same thing is one of the whole points of cpdef
functions, this seems to be going backwards with attributes. Also,
taking Python code and having to change all the names to get Cython
to optimize it (thus rendering it incompatible with pure Python)
seems like an undesirable thing too. Maybe I'm missing something...
- Robert
More information about the Cython-dev
mailing list