Cython:在类型声明中使用导入的类 [英] Cython: using imported class in a type declaration
问题描述
我正在编写Cython 0.23程序,但无法弄清楚如何使用从类型声明中的其他模块导入的 cdef类
。这是重现问题的代码段。
I'm writing a Cython 0.23 program, and I can't figure out how to use a cdef class
that I import from a different module in a type declaration. Here is a snippet that reproduces the problem.
test.py
:
import pyximport
pyximport.install()
from mymodule import *
obj = MyClass(42)
print(obj.field)
print(identity(obj).field)
这按预期工作,并打印 42
两次:
mymodule.pyx
:
cdef class MyClass:
cdef readonly int field
def __init__(self, field):
self.field = field
cpdef MyClass identity(MyClass obj):
return obj
此操作因编译器错误而失败:
This fails with a compiler error:
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
错误:
The error:
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):
^
------------------------------------------------------------
我需要的项目很小,我可以对其进行重构,以便不需要导入该类,但是此解决方案看起来不太干净。有更好的方法吗?
The project I need this for is small and I can refactor it so that I don't need to import the class, but this solution doesn't look very clean. Is there a better way?
推荐答案
您需要使用声明 .pxd文件和 cimport
。 (本质上, cimport
发生在编译时,而 import
发生在运行时,因此Cython无法使用任何东西
You need to use a declaration ".pxd" file and cimport
. (Essentially, cimport
happens at compile time, while import
happens at run time so Cython can't make use of anything imported).
创建 utils.pxd:
Create "utils.pxd":
cdef class MyClass:
cdef readonly int field
utils.pyx现在读取
"utils.pyx" now reads
cdef class MyClass:
def __init__(self, field):
self.field = field
(即删除字段
的声明,因为在.pxd文件)。
(i.e. remove the declaration of field
since it's specified in the .pxd file).
然后放入 mymodule.pyx
from utils cimport MyClass
# other code follows...
这篇关于Cython:在类型声明中使用导入的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!