[Cython] Semantics of cdef int division and %?

Stefan Behnel stefan_ml at behnel.de
Wed Mar 11 14:18:06 CET 2009


Lisandro Dalcin wrote:
> On Wed, Mar 11, 2009 at 5:34 AM, Dag Sverre Seljebotn
> <dagss at student.matnat.uio.no> wrote:
>> Carl Witty wrote:
>>> I just reported http://trac.cython.org/cython_trac/ticket/229, which
>>> points out that division and % on cdef ints have C rather than Python
>>> semantics (for instance, (-1 % 16) is -1 in C, and 15 in Python).
>>>
>>> I'm not sure what the right thing to do here is.  Using C semantics
>>> gives faster code.  Using Python semantics is nicer (whenever I care
>>> about the difference, I always want Python semantics) but slower, and
>>> would be confusing to somebody who was coming from C.
>>
>> I'm +1 on Python semantics. We could make the C version available under
>> some obscure name for any case when one really wants the speed, like
>> cython.fast_c_mod(-1, 16).
>
> I'm no so sure... C is C, Python is Python, and Cython is in the
> middle, but a cdef int is IMHO on C side... Are we going to upcast
> '1/2' to a float?

I agree that this is one of those corner cases where there isn't a clear
case for either Python and C semantics. I do see an interest in having
Python semantics by default (even for C ints), but that might be different
for people coming more from a C background. So there will always be
surprises.

What about supporting an explicit cast like this:

    i = -1 % <unsigned int>16

or at whatever part of that expression it looks better. Maybe

    cdef unsigned int i = -1 % 16

could behave like that, although it does feel weird that the result of an
expression might depend on what it's assigned to...

Stefan



More information about the Cython-dev mailing list