[Cython] Python type assignment errors (was: [cython-users] How to prevent garbage collecting an object?)

Stefan Behnel stefan_ml at behnel.de
Tue Jun 25 06:17:31 CEST 2013


Robert Bradshaw, 25.06.2013 05:15:
> On Mon, Jun 24, 2013 at 3:01 PM, Zak wrote:
>> I have tried a few things, and I always get
>> the error at run-time. Cython is certainly doing type checking, but if the
>> expected type (dict) and the actual type (Python integer) are both Python
>> types and not C types, it seems the error always appears at run-time, never
>> at compile-time. For instance, this compiles fine:
>>
>> cdef dict first_func(int x):
>>     return x
>>
>> cdef int second_func(int x):
>>     cdef dict y
>>     y = first_func(x)
>>     return 5
>>
>> The code above causes a run-time error, but I feel that in an ideal world it
>> should be a compile-time error.
> 
> Yes, it should be.

Agreed. Cython has inherited this behaviour from Pyrex which originally
only knew "object", and we didn't do much about it since. There are rather
fuzzy limits to this, though. For example, this would be stupid but legal
wrt. language semantics:

    cdef dict func():
        return None

    cdef list x = func()

So, the only case that we can really handle is when we know the typed value
originated from a C type that cannot coerce to None nor to the expected
type, i.e. essentially this case:

    cdef int someting = 5
    cdef dict x = something

whereas only slightly more involved code would end up passing through the
analysis, at least for now:

    cdef int something = 5
    cdef dict x = something + 999   # unknown integer size => object

I.e., this can only be handled during coercion of C types to known
(builtin) Python object types, not during assignment - although we do have
the may_be_none() predicate for nodes, and although there's still Vitja's
pending inference rewrite which I didn't have time to look into any
recently. Both can be used to push the fuzzy border a bit further into the
right direction.

Stefan



More information about the cython-devel mailing list