[Pyrex] C versus Python access

Robert Bradshaw robertwb at math.washington.edu
Wed Oct 31 17:14:16 CET 2007


On Oct 30, 2007, at 9:41 PM, Greg Ewing wrote:

> Robert Bradshaw wrote:
>> if you (or someone using your code) creates a  python subclass,  
>> they can override it with a normal python method
>
> How does that work?

You can essentially think of a cpdef method as a cdef method + some  
extras. (That's how it's implemented at least.) First, it creates a  
def method that does nothing but call the underlying cdef method (and  
does argument unpacking/coercion if needed). At the top of the cdef  
method a little bit of code is added to check to see if it's  
overridden. Specifically, in pseudocode

if type(self) has a __dict__:
     foo = self.getattr('foo')
     if foo is not wrapper_foo:
         return foo(args)
[cdef method body]

To detect whether or not a type has a dictionary, it just checks the  
tp_dict slot, which is NULL (by default) for extension types, but non- 
null for instance classes. If the dictionary exists, it does a single  
attribute lookup and can tell (by comparing pointers) whether or not  
the returned result is actually a new function. If, and only if, it  
is a new function, then the arguments packed into a tuple and the  
method called.

It works very well, you should try it out.

- Robert




More information about the Pyrex mailing list