[Cython] Typing of Python objects?

Stefan Behnel stefan_ml at behnel.de
Wed Jan 30 17:26:00 CET 2008


Hi,

Martin C. Martin wrote:
> Are there any plans to add typing and type inference to Python objects 
> in Cython?  For example, it would be great if the following function 
> could call PyDict_SetItemString:
> 
> cdef foo(char *string, mydict):
>      mydict[string] = 5

Note that SetItemString() is not as fast as it might look, as it creates a
Python string internally.


> Of course, we'd need some way to indicate that mydict is a dict. 
> WingIDE uses this:
> 
> cdef foo(char *string, mydict):
>    isinstance(mydict, dict)
>    mydict[string] = 5
> 
> But in a pinch, this would do:
> 
> cdef foo(char *string, mydict):
>    if isinstance(mydict, dict):
>      mydict[string] = 5
>
> Or
> 
> cdef foo(char *string, mydict):
>    assert isinstance(mydict, dict)
>    mydict[string] = 5

None of these is enough. You might just as well have a subclass of a
dictionary, in which case calling PyDict_SetItem() might not do the right
thing. Cython could, however, add this optimisation based on
"PyDict_CheckExact()" at runtime - although that would break compatibility to
Python 2.3... (ok, minus #ifdef's)

I could imagine adding checks for exact types like this: for lists and dicts
on item assignments, and additionally for tuples on item access. Cython
already does things like these in a couple of places. However, it can become
expensive if we add too many conditional branches into simple instructions,
both in terms of time (CPU pipeline and branch prediction) and space (code
size, CPU cache). I do not know how this compares to the performance of the
generic calls.


> For now, I guess I need to do a cdef extern and call 
> PyDict_SetItemString explicitly?

Yes, this is how it currently works (and how it definitely works best).

Stefan



More information about the Cython-dev mailing list