Python class form external module as cdef class

73 views
Skip to first unread message

Martin Bammer

unread,
May 30, 2017, 7:04:33 AM5/30/17
to cython-users
Hi,

I've got a module called MyDefs.py which contains a class like:

class FOO:
    FIRST = 1
    SECOND = 2

Now I want to import this class in another module as a cdef class, so that the cythonized looks like:

if (value == FOO->FIRST) {
...
}

How can this be done?

Best regards,

Martin

Pierre Complex

unread,
May 30, 2017, 6:15:06 PM5/30/17
to cython-users
Hi,

cdef classes cannot inherit python classes, this is explicit in the documentation http://docs.cython.org/en/latest/src/tutorial/cdef_classes.html

Is that what you were trying to achieve? If so, maybe giving more context or motivation might help to suggest alternatives.

Regards,

Pierre

Martin Bammer

unread,
May 31, 2017, 4:15:34 AM5/31/17
to cython-users
Hi,

no I do not want to inherit the Python class. I want to set static types, so that Cython can speedup the class member access with pure C-code.

Regards,

Martin

Pierre Complex

unread,
May 31, 2017, 8:23:34 AM5/31/17
to cython-users
Hello,


On Wednesday, May 31, 2017 at 10:15:34 AM UTC+2, Martin Bammer wrote:
no I do not want to inherit the Python class. I want to set static types, so that Cython can speedup the class member access with pure C-code.


For this purpose, you can make the cdef class inherit from another cdef class, that is not an issue.

Given your example, you might be more interested in "enums" that can also be "cdef-ed": http://cython.readthedocs.io/en/latest/src/reference/language_basics.html?highlight=enum

Regards,

Pierre

Robert Bradshaw

unread,
May 31, 2017, 5:58:03 PM5/31/17
to cython...@googlegroups.com
You cannot "import" a pure Python class as a cdef class; in your example there's no underlying FOO object that provides C-level access to its members. 

If you're OK with enumerating the values, you could do

import module_containing_foo

cdef int FOO_FIRST = module_containing_foo.FOO.FIRST
cdef int FOO_SECOND = module_containing_foo.FOO.SECOND
...

cdef int value = ...
if value == FOO_FIRST:
  ...

which would get you the speed you need. (Substitute object for int if the Python "enum" has arbitrary values.)


--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages