Cython:分享纯python模块

时间:2016-02-24 18:51:34

标签: python cython

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

@cython.cclass
class Test

如何在另一个纯python模块b.py中使用此类?我尝试了from a import Test但是,无论我在Not a type

中使用Test,我都会告诉我b.py

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说的那样,除了.pxd文件之外,您还可以使用.py文件来指定类型。我发现这并不像推杆一样优雅.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