[Pyrex] Extension type initialization

Greg Ewing greg.ewing at canterbury.ac.nz
Mon Mar 14 23:44:13 CET 2005


khinsen at cea.fr wrote:
> I have been playing with extension types in Pyrex a bit and I have come 
> to the conclusion that the __init__ method needs to be a Python function 
> (def) rather than a C function (cdef).
> 
> First question: is this a design choice or a bug?

It's by design. It has to be a Python function, because
it's callable from Python and there is no C slot for it
in the type structure.

The __new__ method does have a type slot, but its
arguments are still passed as Python objects, and there's
nothing that can be done about that.

What you can do is leave the object with no __init__ method
and a __new__ that requires  no arguments, and have another
C method that you call afterwards to initialise it.

By calling the constructor with no arguments, you'll avoid
any type conversion and checking overhead. (An empty tuple
will be needed for the args to __new__, but that's fast
because the empty tuple is cached.)

Hpwever, if you do that, you'll have to be prepared to deal
with the possibility that Python code will instantiate the
type without the C method getting called.

I'm still thinking about ways to improve all this in a
future version.

-- 
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg.ewing at canterbury.ac.nz	   +--------------------------------------+



More information about the Pyrex mailing list