[Pyrex] A problem in generating Python extension types.

Lenard Lindstrom len-l at telus.net
Tue Jan 16 18:21:56 UTC 2007


Daehyok Shin wrote:
> Thanks for your comment.
> In fact, the example I gave was over-simplified.
> The following files show exactly what problems I have.
> As you can see in sample.pyx, I like to directly access a Child object
> from a Parent class in the Python interpreter.
> In addition, I like to create the Child class to have a linked list structure.
>
> When I tried test_sample.py, I got a segment error, probably becase of
> the linked list structure.
> Moreover, I failed to implement the direct access to a contained Child
> object from a Parent object.
> Do you know solutions for them? I would really appreciate your help.
>
>   
>>>>>>>>>>>>>> sample.pyx <<<<<<<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>                             
>
> cdef public class Child[object child_object, type child_type]:
>   cdef public int ID
>   cdef Child child
>
>   def __new__(self):
>     self.child = Child()
>
> cdef public class Parent[object parent_object, type parent_type]:
>   cdef public int ID
>   cdef Child child
>
>   def __new__(self):
>     self.child = Child()
>
>   

You have infinite recursion here. Parent creates a child which creates a 
child and so on. Pyrex initializes the child attribute to None, so it 
can be left alone until you need a child.

>>>>>>>>>>>>> test_sample.py <<<<<<<<<<<<<<<<<<<<<<
>>>>>>>>>>>>>                           
>
> from sample import *
>
> p = Parent()
> p.ID = 10
> p.child.ID=100
> p.child.child.ID=1000
>
> print p.ID, p.child.ID, p.child.child.ID
>
>   

The segment fault would be at "p = Parent()" so excution never got to 
the attribute accesses.

There are two ways to make the child attribute visible from Python. 
First declare it as "public object". But now child can be any python 
object. Also, any private Child fields are no longer directly accessible 
from a Parent instance. The Child instance has to be assigned to a "cdef 
Child" variable first.

The other way is to have a child property instead. See the Properties 
section of "Extension Types" in the Pyrex documentation. A child 
property can check for end-of-list, a None, and create a new Child instance.

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




More information about the Pyrex mailing list