我正在尝试将一个项目迁移到 Python 3.4,但我在理解和实现 Python3 丰富的比较功能时遇到了问题。该项目实现了一个C库的Python扩展
我是 Python 的新手,我已经有 15 年没有接触过任何 C 了
我没有写原始项目,它被放弃了。它在 2012 年只有一次提交,它基于另一位作者 2006 年的作品。但是,该项目完全符合我的要求,所以我很想恢复和更新它。
我已经能够将代码更新到 Python 2.7 并且没有错误地构建并让它运行并通过测试。我还创建了一个 Python 3.4 分支,现在可以正常构建了。这是通过基本上查找编译器抛出的每个错误和警告并实现建议的修复来完成的。
但是,当我在编译后使用 Python 3.4 导入库时:
python3 setup.py install
我收到以下错误:
>>> import _suffix_tree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Type _suffix_tree.SuffixTreeNode defines tp_reserved
(formerly tp_compare) but not tp_richcompare. Comparisons may not behave as intended.
查看扩展确实没有 tp_richcompare 实现,所以我尝试添加它。 我已经尝试实现我在网上找到的几种解决方案,但都没有奏效,而且我对这个问题的了解不够,无法在没有帮助的情况下解决它。我尝试过实现所需的丰富比较功能,但没有成功。我尝试过的一个例子是:
static PyObject* Node_richcmp(NodeObject *n1, NodeObject *n2, int op);
static PyObject* Node_richcmp(NodeObject *n1, NodeObject *n2, int op)
{
return (int)(n1->node - n2->node);
}
Node_richcmp, /* tp_richcompare */
但是我得到如下错误:
python_bindings.c:218:2: warning: initialization from incompatible pointer type [enabled by default]
Node_richcmp, /* tp_richcompare */
^
python_bindings.c:218:2: warning: (near initialization for 'NodeType.tp_richcompare') [enabled by default]
python_bindings.c: In function 'Node_richcmp':
python_bindings.c:418:5: warning: return makes pointer from integer without a cast [enabled by default]
return (int)(n1->node - n2->node);
^
现在我根据错误和一些搜索猜测我弄乱了值与地址的分配,但我不确定这是否正确或如何修复它。
谁能帮我实现所需的丰富比较方法?
我尝试过以下资源:http://py3c.readthedocs.org/但我就是不明白。
项目的完整代码可以在这里找到:https://github.com/mattporritt/suffix-tree-unicode在 python_34 分支上
最佳答案
您不能只复制以前的tp_compare
实现。 tp_richcompare
有一个 considerably different contract .它(通常)返回 Py_True
或 Py_False
而不是 -1
、0
或 1
及其返回值应取决于所请求的比较 (op
)。
关于python - Migrate extension to python3,丰富对比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35529462/