[Pyrex] Opaque structures and Extension Types

Lenard Lindstrom len-l at telus.net
Thu May 15 05:38:10 CEST 2008


Robert Bradshaw wrote:
> On May 14, 2008, at 4:47 PM, Greg Ewing wrote:
>
>   
>> Roberto Cavada wrote:
>>
>>     
>>> My way of handling allocation and
>>> initialization of classes in C would require that __cinit__ of
>>> derived class would be not called at all, as for example
>>> Worker_create already handles the allocation and initialization of
>>> Person and Worker structures.
>>>       
>> I think you'll just have to initialise the struct in
>> __init__ rather than __cinit__, then you'll get
>> control over whether the base class __init__ is
>> called or not.
>>
>> It's not entirely safe, but it's about the best that
>> can be done until I do something about providing a
>> more Python-like __new__ method.
>>     
>
> One can also make a cdef method which the (only) baseclass __cinit__  
> calls, and simply override this for the subclass. One would want to  
> do the same with deallocation as well.
>
>   
Maybe that works with Cython, but not Pyrex.

# test.pyx
cdef class Root:
    cdef int value
    def __cinit__(self):
        self.initialize()
    def get_value(self):
        return self.value
    cdef initialize(self):
        self.value = 0

cdef class A(Root):
    cdef initialize(self):
        self.value = 1

cdef class B(A):
    cdef initialize(self):
        self.value = 2

 >>> import test
 >>> test.Root().get_value()
0
 >>> test.A().get_value()
0
 >>> test.B().get_value()
0

C method calls from __cinit__ are not virtual. The vtable of a child 
extension type is set only after all the __cinit__ methods of its parent 
classes are called.

-- 
Lenard Lindstrom
<len-l at telus.net>




More information about the Pyrex mailing list