[Pyrex] Subclassing a non-GC type

Robert Bradshaw robertwb at math.washington.edu
Wed Jan 30 10:22:59 CET 2008


On Jan 28, 2008, at 11:57 PM, Lenard Lindstrom wrote:

> Greg Ewing wrote:
>> Lenard Lindstrom wrote:
>>
>>
>>> Looking at the inherit_special function in typeobject.c I see that
>>> PyType_Ready promotes tp_traverse,  tp_clear and HAVE_GC.
>>>
>>
>> In that case, it should be sufficient to just omit tp_traverse,
>> tp_clear and HAVE_GC on any type that doesn't have Python
>> valued C attributes.
>>
>> I think the reason I didn't do that initially was that
>> PyType_Ready didn't do all the right things back then, and
>> not fully understanding what was going on, I didn't want
>> to be too clever.
>>
>>
> PyType_Ready does plenty of clever things like fill tp slots when
> special methods are found and add special methods when tp slots are
> filled. It handles all the inheritance requirements to make an  
> extension
> type look like a new-style class.

The code now is a bit more clever than that. Say one has

cdef class A:
     cdef object a

cdef class B(A):
     pass

cdef class C(B):
     pass

cdef class D(C):
     cdef object d

The tp_new/clear/traverse/dealloc slots for D need to be implemented  
to handle the member d, and recursively call up to handle A.a. But  
since B and C don't have any attributes, it calls directly to A's  
slots, and what's even better is that if A and D are in the same  
module, it will call by function name (rather than the pointer in the  
type object) which facilitates inlining by the C compiler (as these  
are all tiny functions).

- Robert




More information about the Pyrex mailing list