python 创建对象数组_如何创建一个固定长度,在用Cython Python对象的可变数组?...

博客讨论了如何在Python中创建一个固定长度但可变的数据结构,类似于元组但可修改。作者遇到的问题是不希望使用列表,因为担心额外元素的内存开销会随着数据增长而快速增加。解决方案是使用Cython创建一个包含PyObject指针的数组,并手动管理引用计数,确保数组大小固定且元素可变。这涉及到在Cython类中定义一个PyObject指针数组,初始化时填充对象并增加引用计数,在析构时释放这些对象。
摘要由CSDN通过智能技术生成

I need to have an array of python objects to be used in creating a trie datastructure. I need a structure that will be fixed-length like a tuple and mutable like a list. I don't want to use a list because I want to be able to ensure that the list is exactly the right size (if it starts allocating extra elements, the memory overhead could add up very quickly as the trie grows larger). Is there a way to do this? I tried creating an array of objects:

cdef class TrieNode:

cdef object members[32]

...but that gave an error:

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

What is the best way to do what I'm trying to do?

解决方案

I don't know about the best solution, but here's a solution:

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(temp_object)

self.members[i] = temp_object

def __init__(self):

# just to show that it works...

for i in range(SIZE):

print 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

A Cython object is an automatically refcounted PyObject *. You can always roll your own arrays of PyObject *'s as long as you take responsibility for refcounting the little buggers. This can be a major headache for non-trivial cases.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值