python - Cython:在类型声明中使用导入的类

标签 python cython

我正在编写 Cython 0.23 程序,但我不知道如何使用从类型声明中的不同模块导入的 cdef 类。这是重现该问题的代码片段。

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
<小时/>

由于编译器错误而失败:

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):
                      ^
------------------------------------------------------------

我需要这个的项目很小,我可以重构它,这样我就不需要导入该类,但这个解决方案看起来不太干净。有更好的办法吗?

最佳答案

您需要use a declaration ".pxd" file和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 文件中指定的)。

然后在mymodule.pyx

from utils cimport MyClass
# other code follows...

关于python - Cython:在类型声明中使用导入的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33616927/

相关文章:

python - "Cannot convert Python object argument to type ' <typename> '"- 使用 Cython 包装 C++ 类时出错

Python 脚本是否应该以换行结尾? Pylint自相矛盾?

python - 使用Scrapy时如何导出为csv?

python - 使用 Python/C 接口(interface)而不是 Cython 是否有优势?

python - 带有 cython 的 numpy 数组

Python/Cython 导入文件和方法时遇到问题

python - 尝试编写 C++ 包装函数时无法在 Cython 中将 Numpy 数组转换为 OpenCV Mat

Python 与谷歌应用引擎。属性错误 : 'module' object has no attribute 'HTTPSHandler' error message

python - Selenium 错误 : Element not found in the cache - perhaps the page has changed since it was looked up

python - Cygwin gcc 问题 - 找不到 Python.h