Cython: how to make an python object as a property of cython class Cython: how to make an python object as a property of cython class python python

Cython: how to make an python object as a property of cython class


I don't think you can (http://docs.cython.org/src/userguide/sharing_declarations.html#sharing-extension-types) but you can work-around it using __cinit__ to assert that the attribute has the correct type. The declaration cdef public object x of the extension type attribute has the following meaning:

In your Cython file (named "p.pyx" for example):

import my_python_module as qcdef class Y:    cdef int i    cdef public object x  # public so it can be accessed from Python    def __cinit__(self, x_):        assert isinstance(x_, q.X)        self.x = x_

and my_python_module.py is where you have defined your class X:

class X(object):    def __init__(self):        self.i = 1

Then, you use it like this:

import my_python_module as qimport py = p.Y(q.X())print y.xprint y.x.i

Also, note that cpdef means the same as cdef as of cython == 0.29.22, and will not be supported in cython == 3 (Cython issue 3959, and the warning that cython == 0.29.22 prints if an attribute is declared with cpdef; see also the changelog entry for that Cython version).


I would use something like this:

cdef class SomeCls:    cdef object _x    def __cinit__(self, x_):        self._x = x_    property x:        def __get__(self):            return self._x        def __set__(self, x_):            self._x = x_

The above is especially useful when exposing attributes of an extern struct or class. Refer to example here:wrapping C++