【问题标题】:subclassing cython class: pxd file not found when 'cimport'ing子类化 cython 类:“cimport”时找不到 pxd 文件
【发布时间】:2017-07-27 17:10:52
【问题描述】:

我刚刚在 cython 中偶然发现了一些奇怪的行为,我希望有人能够启发我。

我有两个包 A 和 B,它们都是使用 distutils 构建的,因为我有几个 cython 类(其中许多包含 c++ 类)。

在包 A 中,我有一个名为 BaseAClass 的 cython 类,在 .pxd 文件中声明并在相应的 .pyx 中完全声明。我在包 A 中有许多其他类是 BaseAClass 的子类。

现在在包 B 中,我已经能够构建采用 BaseAClass 成员的类,只需这样做

# in package B tree, .pyx file
cimport A.stuff._A as _A
cdef BClass(object):
    cdef _A.BaseAClass my_aclass
    def __cinit__(self, aclass):
        self.my_aclass = aclass

我在编译和使用这些类时没有问题。

但是,如果我尝试在包 B 中继承 BaseAClass

# in package B tree, .pyx file
cimport A.stuff._A as _A
cdef BClass(_A.BaseAClass):
    """put a constructor here"""

我尝试 cythonize 我得到错误'_A.pxd' not found。但是,如果我这样做了

# in package B tree, .pyx file
cdef BClass(A.stuff._A.BaseAClass):
    """put a constructor and methods here"""

没问题!希望有人知道发生了什么!

请注意,当我编译时,我传递了额外的标志“-I /path/to/packageA/stuff”以确保包 A 中的 pxd 文件可用于包 B。另请注意,我使用了类似的 cythonize。 py 用于 scipy 并且我已经到处都有 __init__.py 文件,我什至尝试添加一个 __init__.pxd 文件但它没有帮助。

【问题讨论】:

    标签: python cython distutils setup.py cythonize


    【解决方案1】:

    导入应写为from stuff cimport _A,其中stuff.pxd 是与执行导入的.pyx 文件位于同一目录中的定义文件。

    cimport A.stuff._A as _A 行使 Cython 查找名为 _A.pxd 的定义文件,这可能是意外行为。

    首先,Cython 可能不应该接受 cimport X.sub_package as Y 形式的导入。

    【讨论】:

    • 当你cimport numpy as np 怎么样?例如见here
    • 我的意思是不应该接受cimport XX.something.something_else as YY 的形式。常规的 cimport X as Y 有效,但子包无效。要么正确处理这种情况。可能值得在 Cython 回购中提出它。
    猜你喜欢
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    相关资源
    最近更新 更多