[Cython] Extension Type Question
Robert Bradshaw
robertwb at math.washington.edu
Tue Mar 25 23:06:40 CET 2008
On Mar 25, 2008, at 1:05 PM, David J. C. Beach wrote:
> Cython developers,
>
> I knew about Pyrex a few years ago but only recently discovered
> Cython. I'm very glad to see that there is an active community
> involved in adding these features to Pyrex.
Thanks.
> I've been trying to cut my teeth on Pyrex/Cython by writing a few
> extension types, and have encountered some confusion about whether the
> "self" argument needs to be given an explicit type. This short
> example illustrates my confusion:
>
> cdef class IntBox:
>
> cdef int _data
>
> def __init__(self, int value=0):
> self._data = value
>
> def __add__(IntBox self, IntBox other not None):
> cdef IntBox result = IntBox(self._data + other._data)
> return result
>
> def __repr__(self):
> return str(self._data)
>
>
> In this code, the __init__() and __repr__() methods have no problem
> accessing self._data.
>
> However, if I exclude the "IntBox" type before the self argument in
> the __add__() method, the code doesn't run. (It fails at runtime by
> saying that it is unable to access the member "_data". (Presumably,
> this is because Cython compiled it as a python dictionary attribute
> lookup, instead of using the cdef'd storage.)
>
> My questions are:
>
> - Why am I seeing this behavior?
> - What is the best practice concerning the "typing" of the self
> parameter? Should I always write "IntBox self" as the first argument
> to each method of the IntBox class? (Even though it appears to only
> be *sometimes* necessary?)
>
> Thank you for your help in this confusing matter.
See the "arithmatic operators" at http://www.cosc.canterbury.ac.nz/
greg.ewing/python/Pyrex/version/Doc/Manual/special_methods.html .
This is because of the nature of the Python/C API, and though there's
talk of emulating the __add__/__radd__ paradigm of Python it's
unclear how one would do so.
Self is always the right type otherwise.
- Robert
More information about the Cython-dev
mailing list