[Pyrex] cdef'd classes initialization

Lenard Lindstrom len-l at telus.net
Fri Aug 11 04:15:34 UTC 2006


On 10 Aug 2006 at 14:36, Daniele Varrazzo wrote:

> I stumbled against the Pyrex __new__ peculiar behavior: all the 
> superclasses' __new__ get called and no communication is available in 
> the calls chain.
> 
> For example, in my library each subclass of a base class must allocate 
> some heap space: different subclasses require different amount of space.
> 
> Should the space be allocated by the base class __new__? I think it 
> should, but how can a subclass tell the base class how much to allocate? 
> __new__'s parameters can't be altered.
> 
If none of the subclasses need to declare extra C fields then they 
could be regular classes. Then the __new__ behaviour will work 
correctly.

-------------- someinit.pyx ---------
cdef class CRoot:
    cdef public int datum

    def __new__(self, datum):
        self.datum = datum

def C___new__(cls, value):
    return CRoot.__new__(cls, value * 2)
C___new__ = staticmethod(C___new__)
class C(CRoot):
    __new__ = C___new__
--------------------------------------
>>> from someinit import *
>>> croot=CRoot(10)
>>> c=C(10)
>>> croot.datum
10
>>> c.datum
20

[snip]
> > cdef class CRoot:
> >     """For factory function"""
> >     cdef int datum
> > 
> >     def get_datum(self):
> >         return self.datum
> > 
> > def make_object(int datum):
> >     cdef CRoot o
> >     o = CRoot()
> >     o.datum = datum
> >     return o
> > 
> > cdef class C(CRoot):
> >     """Has allocator/deallocator"""
> >     def __new__(self, int datum):
> >         self.datum = datum
> > 
> >     def __dealloc__(self):
> >         pass
> 
> This is not the first time i am faced to the need to hide an extension
> type to be directly exposed to Python: in your example would it be
> possible to hide CRoot from the module dict?
> 
Not that I know of. You could wrap the Pyrex module with a Python 
module and only import those items you want to expose.

Lenard Lindstrom
<len-l at telus.net>





More information about the Pyrex mailing list