TAGS :Viewed: 6 - Published at: a few seconds ago

[ Share extension types in Cython for static typing ]

I converted a Python class to an extension type inside a .pyx file. I can create this object in the other Cython module, but I can't do static typing with it.

Here is a part of my class:

cdef class PatternTree:

    cdef public PatternTree previous
    cdef public PatternTree next
    cdef public PatternTree parent
    cdef public list children

    cdef public int type
    cdef public unicode name
    cdef public dict attributes
    cdef public list categories
    cdef public unicode output

    def __init__(self, name, parent=None, nodeType=XML):
        # Some code

    cpdef int isExpressions(self):
        # Some code

    cpdef MatchResult isMatch(self, PatternTree other):
        # Some code

    # More functions...

I have tried using a .pxd file to declare it, but it says "C method [some function] is declared but not defined" on all of my functions. I have also tried stripping the C stuff in the functions of my implementation to make it act like an augmented class, but that didn't work either.

Here is my .pxd as it stands:

cdef class PatternTree:
    cdef public PatternTree previous
    cdef public PatternTree next
    cdef public PatternTree parent
    cdef public list children

    cdef public int type
    cdef public unicode name
    cdef public dict attributes
    cdef public list categories
    cdef public unicode output

    # Functions
    cpdef int isExpressions(self)
    cpdef MatchResult isMatch(self, PatternTree other)

Thanks for your help!

Answer 1


I found out a fix for it. Here is the solution:

In .pyx:

cdef class PatternTree:

    # NO ATTRIBUTE DECLARATIONS!

    def __init__(self, name, parent=None, nodeType=XML):
        # Some code

    cpdef int isExpressions(self):
        # Some code

    cpdef MatchResult isMatch(self, PatternTree other):
        # More code

In .pxd:

cdef class PatternTree:
    cdef public PatternTree previous
    cdef public PatternTree next
    cdef public PatternTree parent
    cdef public list children

    cdef public int type
    cdef public unicode name
    cdef public dict attributes
    cdef public list categories
    cdef public unicode output

    # Functions
    cpdef int isExpressions(self)
    cpdef MatchResult isMatch(self, PatternTree other)

In whatever Cython module (.pyx) I want to use this for:

cimport pattern_tree
from pattern_tree cimport PatternTree

One final word of warning: Cython does not support relative importing. This means that you have to supply the entire module path relative to the main file you're executing from.

Hopes this helps somebody out there.