Cython:共享纯 python 模块

Cython: share pure python module

我有一个纯 python 模块 a.py 文件,其中包含一个用 cython 增强的 class:

@cython.cclass
class Test

如何在另一个纯 python 模块 b.py 中使用此 class?我试过 from a import Test 但是 cython 编译器告诉我 Not a type 我在 b.py

中使用 Test 的任何地方

正如我在评论中所说,除了 .py 文件之外,您还可以使用 .pxd 文件来指定其中的类型。我意识到这并不像放置那样优雅.py 文件中的所有内容,但据我所知这是你能做的最好的。

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

您可以通过检查生成的 b.c 文件来验证它是否正确使用了类型信息。

供参考,相关文档为http://docs.cython.org/src/tutorial/pure.html#magic-attributes-within-the-pxd