python的cdef类列表,避免全部显式转换

时间:2015-02-02 17:11:50

标签: python types cython

我正在外部C库周围编写一个Cython包装器。该库生成一个树数据结构(它是一个HTML解析器),Cython代码需要构建二级树并遍历它们。所以我有这样的类定义:

cdef class TreeNode:
    cdef list children  # List<TreeNode>

    cpdef debug_dump(TreeNode self, object fp)

    # ... other fields and methods ...

然后执行以下操作的方法:

cpdef debug_dump(TreeNode self, object fp):
    fp.write("... stuff about self ...")

    for c in self.children:
        (<TreeNode>c).debug_dump(fp)

这一切都有效,但我发现自己不得不在该死的地方写(<TreeNode>x)。在某些情况下,它变得非常荒谬:

# Otherwise, this block might be mergeable with its immediate
# previous sibling.
else:
    pclass = (<TreeNode>(<TreeNode>self.stack[-1]).children[-1]).tagclass
    if (tclass == pclass or (tclass == TC_PARA and pclass == TC_HEADING)):
        self.stack.append((<TreeNode>self.stack[-1]).children.pop())
        (<TreeNode>self.stack[-1]).tagclass = TC_PARA
        (<TreeNode>self.stack[-1])._depth = <int>depth

有没有办法声明一个变量是一个具体类型的列表,所以我不必在这个地方撒上这些演员?

(注意:我已经意识到在vector<TreeNode>模式下使用--cplus的可能性,但这是一个外部库的接口,我不确定它&#39}可以安全地使用C ++中的标题,所以我更喜欢不涉及--cplus模式的解决方案。将来可能还需要将这些列表暴露给正常解释的Python代码,AFAIK不能与vector合作。)

0 个答案:

没有答案