[Cython] cpdef, nogil and void return (was: [cython-users] Use the function abs in a cpdef function with nogil)

Stefan Behnel stefan_ml at behnel.de
Sat Sep 22 15:03:11 CEST 2012


[CC-ing cython-devel here as this is a design issue]

Joaquin Cuenca Abela, 21.09.2012 19:32:
> On Fri, Sep 21, 2012 at 6:12 PM, Chris Barker wrote:
>> On Fri, Sep 21, 2012 at 2:48 AM, Joaquin Cuenca Abela wrote:
>>> I don't set a return type, it gives the error:
>>>
>>> cpdef undo_filter_sub(int filter_unit, unsigned char[:] scanline,
>>>      ^
>>> ------------------------------------------------------------
>>> cpngfilters.pyx:10:6: Function with Python return type cannot be declared nogil
>>
>> cpdef means build both a pyton function and a C function -- C
>> functions need a return type. Cython defaulats to a generic Python
>> object as a return type, which could cause issue with nogil, so it
>> won't let you do that -- so try declareing a void return type:
>>
>> cpdef void undo_filter_sub(int filter_unit, unsigned char[:] scanline,
>>
>> I suspect that will give you None for the Python version, but I'm just
>> guessing here.
>>
>> If that doesn't work, use int or something, and ignore the return value.
>
> nope, with void I was getting "Cannot convert 'void' to Python
> object". What I did is put int and return 0, maybe this should be
> added to the docs.

I think we should support "cpdef void func()" and just let the Python
wrapper return None automatically. That's the expected Python equivalent of
returning nothing. Shouldn't be hard to implement.

cpdef functions that are also declared nogil are somewhat unusual, but I
don't see them being outright wrong. Basically, it would allow you to call
them from Cython code with or without holding the GIL as well as directly
from Python code (that always holds the GIL). Might be handy for avoid code
redundancy in some cases.

Patches welcome, as always.

Note, however, that declaring the return type as void will make exception
handling more difficult. That's ok for a nogil function, which cannot raise
exceptions, but it's worth remembering for normal functions.

Stefan



More information about the cython-devel mailing list