[Pyrex] extension type attributes
Lenard Lindstrom
len-l at telus.net
Fri May 29 19:29:43 CEST 2009
horace wrote:
> hi,
>
> i have a question about extension type attributes.
>
> cdef class MyComplex:
> """A mutable complex number type (incomplete)"""
> cdef complex *c
>
> do all attributes have to be cdef? if i want to have a python object
> as an attribute i have to use
>
> cdef object mypythonobject
>
> and then initialize it in __init__()? or did i misunderstand
> something? i didn't find the manual very clear about this.
>
> (i use cython in case this makes any difference.)
>
Hi,
The familiar object attributes of Python class instances - class
Something - are stored in a per object dictionary keyed by attribute
name. To see this dictionary just do obj.__dict__ for some object
created from a Python class. Extension types, at least Pyrex/Cython
extension types, don't have that dictionary. And I don't see any way
directly enable it. Extension type "attributes" are really just C
structure fields, so not directly accessible from Python. There are the
public and readonly qualifiers that automatically create properties for
a cdef attribute though. So is you what an object attribute accessible
form Python do something like this:
cdef class MyClass:
cdef public object x
Attribute x can now be read and altered from Python. Initialize it
either from __cinit__ or __init__. It will default to None.
If you don't know what the valid attributes will be before hand, then
the easiest way to add object attributes is to subclass the extension
type with a normal class:
cdef class _MyClass:
.....
class MyClass(_MyClass):
....
Now the MyClass class has a per object dictionary. Use __init__ to set
initial values. Make sure the class __init__ function and extension type
__cinit__ have compatible arguments or one of them will complain.
Lenard Lindstrom
<len-l at telus.net>
More information about the Pyrex
mailing list