Greg Ewing, 28.06.2010 11:12:
> Craig Citro wrote:
>> you could write a function
>> that takes an arbitrary Python object, but decide that you "know" it
>> will only ever get called with a dict, and directly dispatch to
>> various PyDict_* macros
>
> Pyrex will do this if you declare the object as being of
> type 'dict' (and it will check the type on the boundary
> between Python and extension code, so it's still type-safe).
> Similarly for 'list' and a few other built-in types that
> have dedicated C APIs.

Right, this is totally not "black magic".

There are some cases, though, where you can easily write C-API code that 
outperforms Cython code. A well known example is a call to PyDict_GetItem() 
in C and a subsequent check for a NULL return value. Cython code needs to 
read the value into a variable first and then test it, a common idiom being

     result = d.get(key)
     if result is not None:
        ...

So the compiler would need to know that the None return value is no longer 
used later on, i.e. can safely be allowed to be NULL instead of None, so 
that it can generate simpler code without additional ref-counting overhead, 
and the C compiler can see more directly what happens. It's even worse for 
the exception catching idiom:

     try:
         result = d[key]
     except KeyError:
         pass
     else:
         ...

which is a relatively efficient (and therefore common) way to do it in 
Python, but could really collapse into a single call to PyDict_GetItem() 
plus a NULL check in the generated C code. Cython isn't that smart yet.

But in general, this is really chasing microseconds in places where it 
rarely matters.

Stefan
_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to