我正在编写 Cython 0.23 程序,但我不知道如何使用cdef class
我在类型声明中从不同的模块导入。这是重现该问题的片段。
test.py
:
import pyximport
pyximport.install()
from mymodule import *
obj = MyClass(42)
print(obj.field)
print(identity(obj).field)
这按预期工作并打印42
twice:
mymodule.pyx
:
cdef class MyClass:
cdef readonly int field
def __init__(self, field):
self.field = field
cpdef MyClass identity(MyClass obj):
return obj
这会失败并出现编译器错误:
mymodule.pyx
:
from utils import MyClass
cpdef MyClass identity(MyClass obj):
return obj
utils.pyx
:
cdef class MyClass:
cdef readonly int field
def __init__(self, field):
self.field = field
错误:
Error compiling Cython file:
------------------------------------------------------------
...
from utils import MyClass
cpdef MyClass identity(MyClass obj):
^
------------------------------------------------------------
mymodule.pyx:3:6: 'MyClass' is not a type identifier
Error compiling Cython file:
------------------------------------------------------------
...
from utils import MyClass
cpdef MyClass identity(MyClass obj):
^
------------------------------------------------------------
我需要这个的项目很小,我可以重构它,这样我就不需要导入类,但这个解决方案看起来不太干净。有没有更好的办法?
你需要使用声明“.pxd”文件 http://docs.cython.org/src/userguide/sharing_declarations.html and cimport
。 (本质上,cimport
发生在编译时,同时import
发生在运行时,因此 Cython 无法使用导入的任何内容)。
创建“utils.pxd”:
cdef class MyClass:
cdef readonly int field
“utils.pyx”现在显示为
cdef class MyClass:
def __init__(self, field):
self.field = field
(即删除声明field
因为它是在 .pxd 文件中指定的)。
Then in mymodule.pyx
from utils cimport MyClass
# other code follows...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)