我需要一个 python 对象数组来创建一个 trie 数据结构。我需要一个像元组一样固定长度、像列表一样可变的结构。我不想使用列表,因为我希望能够确保列表的大小完全正确(如果它开始分配额外的元素,内存开销可能会很快增加,因为trie 变得更大)。有没有办法做到这一点?我尝试创建一个对象数组:
cdef class TrieNode:
cdef object members[32]
...但这给出了一个错误:
Error compiling Cython file:
------------------------------------------------------------
...
cdef class TrieNode:
cdef object members[32]
^
------------------------------------------------------------
/Users/jason/src/pysistence/source/pysistence/trie.pyx:2:23: Array element cannot be a Python object
做我想做的事情的最佳方法是什么?
最佳答案
我不知道最佳解决方案,但这是一个解决方案:
from cpython.ref cimport PyObject, Py_XINCREF, Py_XDECREF
DEF SIZE = 32
cdef class TrieNode:
cdef PyObject *members[SIZE]
def __cinit__(self):
cdef object temp_object
for i in range(SIZE):
temp_object = int(i)
# increment its refcount so it's not gc'd.
# We hold a reference to the object and are responsible for
# decref-ing it in __dealloc__.
Py_XINCREF(<PyObject*>temp_object)
self.members[i] = <PyObject*>temp_object
def __init__(self):
# just to show that it works...
for i in range(SIZE):
print <object>self.members[i]
def __dealloc__(self):
# make sure we decref the members elements.
for i in range(SIZE):
Py_XDECREF(self.members[i])
self.members[i] = NULL
Cython object
是一个自动引用的 PyObject *
。只要您负责对小错误进行重新计数,您就可以随时滚动自己的 PyObject *
数组。对于非平凡的情况,这可能是一个令人头疼的问题。
关于python - 如何在 Cython 中创建固定长度、可变的 Python 对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4834036/