简体   繁体   中英

Cython: share pure python module

I have one pure python module a.py file containing a class enhanced with cython:

@cython.cclass
class Test

How can I use this class in another pure python module b.py ? I tried from a import Test but then the cython compiler tells me Not a type wherever I use Test in b.py

As I said in the comments, you can do it by using .pxd files in addition to the .py files to specify the types in. I realise this isn't as elegant as putting everything in the .py files, but as far as I know it's the best you can do.

a.py:

class Test:
    pass

a.pxd:

cdef class Test:
  pass

b.py:

# here I use Test in all the places I think you could want to use it:
#   as a function argument
#   as a variable in a function
#   in a class
import a

def f(x):
    return x

def g():
    t = a.Test()
    return t

class C:
    pass

b.pxd:

import cython
cimport a

cpdef f(a.Test x)

@cython.locals(t=a.Test)
cpdef g()

cdef class C:
    cdef a.Test t

You can verify that it's using the type information correctly by inspecting the generated bc file.

For reference, the relevant documentation is http://docs.cython.org/src/tutorial/pure.html#magic-attributes-within-the-pxd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM