[Cython] [cython-users] Confused by user's guide

Robert Bradshaw robertwb at gmail.com
Tue Aug 13 06:13:09 CEST 2013


On Mon, Aug 12, 2013 at 1:37 AM, Zak <cython at m.allo.ws> wrote:
> I bet some people are still confused, because I would have been confused if
> I read that a few months ago. Let me explain with code:
>
> # This is a Python function:
> def do_math(top, bottom):
>     return top / bottom
>
> # This is also a Python function:
> def do_math2(int top, int bottom):
>     return top / bottom
>
> # The function do_math2 above is "actually" doing
> # something like this:
> def do_math3(top_temp, bottom_temp):
>     cdef int top = top_temp
>     cdef int bottom = bottom_temp
>     return top / bottom
>
> All 3 functions above are Python functions, they take Python objects as
> arguments and they return a Python object. The static type annotations in
> do_math2 can be thought of as syntactic sugar - these type annotations do
> not change the call signature of the function, they just tell the function
> to immediately convert those arguments into C integers. When the function is
> called, it is called with Python objects for top and bottom. But inside the
> function, it will use fast C integers for top and bottom. Without this
> syntactic sugar, you would be forced to do a renaming dance like that shown
> in do_math3.

Good explanation. These days do_mat2 actually equivalent to

def do_math2(top_temp, bottom_temp):
    cdef int top = top_temp
    cdef int bottom = bottom_temp
    return do_math_c(top, bottom)

cdef do_math_c(int top, int bottom):
    return top / bottom

which doesn't really matter to the user except that there may be some
cases (in the future) where we can extract and call do_math_c
directly.

Of course, this is exactly what cpdef is, which has got me thinking
whether we need a separate keyword for this, or if we could simply
make all def functions cpdef automatically. One place that's different
is for exported cdef classes where c(p)def methods must be declared in
the .pxd file, but we could perhaps handle this case by allowing them
to be declared as plain cdef (or "def") methods there. Does anyone see
any drawbacks to this? (I suppose there's a little overhead in the
check-if-overridden dispatch.)

- Robert


More information about the cython-devel mailing list