如何处理Cython ValueError

Ger*_*ncy 5 python cython

我对Cython扩展类型相当新,并且对运行时抛出的以下与Cython相关的ValueError感到困惑:

ValueError: vrptwms.node.Node has the wrong size, try recompiling
Run Code Online (Sandbox Code Playgroud)

Node类在vrptwms目录中的文件node.pxd和node.pyx中定义.前者的内容是

cdef class Node:
    """
    docstring
    """
    cdef public float x, y, demand
    cdef public float earliest_start, latest_start, servicetime
    cdef public int id
Run Code Online (Sandbox Code Playgroud)

而后者的是(我暂时删除所有希望追查问题的类型声明)

cdef class Node:
    """
    Represents either a customer or the depot.
    """
    # pylint: disable-msg=C0103, R0913

    def __init__(self,
                id_,
                x,
                y,
                demand,
                earliest_start,
                latest_start,
                servicetime):
        """
        docstring
        """
        self.x = float(x)
        self.y = float(y)
        self.demand = float(demand)
        self.earliest_start = float(earliest_start)
        self.latest_start = float(latest_start)
        self.servicetime = float(servicetime)
        self.id = int(id_)

    # some internal functions
Run Code Online (Sandbox Code Playgroud)

然后,第三个文件problemreader.pyx包含节点类,方法如下:

from vrptwms.node cimport Node
from vrptwms.node import Node
Run Code Online (Sandbox Code Playgroud)

编译没有任何问题.setup.py包含

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension("route", ["fastroute.pyx"]),
            Extension("node", ["node.pyx", "node.pxd"]),
            Extension("problemreader", ["problemreader.pyx"]),
            ]

setup(
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
)
Run Code Online (Sandbox Code Playgroud)

我还尝试将node.pxd添加到问题阅读器扩展,但没有成功.在以下生成的C代码中引发了该问题

  __pyx_ptype_7vrptwms_4node_Node = __Pyx_ImportType("vrptwms.node", "Node", sizeof(struct __pyx_obj_7vrptwms_4node_Node), 1); if (unlikely(!__pyx_ptype_7vrptwms_4node_Node)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
Run Code Online (Sandbox Code Playgroud)

和原因

Traceback (most recent call last):
  File "./cli.py", line 16, in <module>
    from vrptwms.problemreader import ProblemReader
  File "node.pxd", line 9, in init problemreader (problemreader.c:4991)
    cdef class Node:
ValueError: vrptwms.node.Node has the wrong size, try recompiling
Run Code Online (Sandbox Code Playgroud)

我多次删除了所有生成的.c,.so和.o文件,但无法解决问题.非常感谢任何提示(包括我可能错过的任何文档链接).

编辑:如果我使用旧样式相对导入(例如导入节点而不是vrptwms.node)并删除init .py文件,则问题不会重现- 因此源本身没有任何问题.我创建了一个小的测试用例来重现这个问题:c_test.tar.gz(需要提取到PYTHONPATH上的目录)和一个几乎相同的情况,而不使用不能重现它的包:c_test_w.tar. gz.

Ger*_*ncy 2

Robert Bradshaw 在cython 用户邮件列表上提出了一些提示。最重要的是,手动(重新)编译 .pyx 文件并cython *.pyx运行原始安装脚本是可行的。还有一种编写CEP 201 - Distutils 预处理中描述的安装脚本的更新方法,它应该有所帮助,但在我当前使用 Cython 0.14.1 的设置中不起作用。