【发布时间】:2015-08-19 05:08:51
【问题描述】:
我正在尝试创建一个继承自 int 或 cython.int 的扩展类型。这对我来说是必要的,因为我需要能够将此类型用作某些列表/数组的索引。
这是在 Anaconda 上使用 Cython v0.22 重现 Python 2.7.9 Win32(我正在运行 Windows 7)上的错误的代码:
import cython
cimport cython
import sys
cdef class ExtendedInt(int):
#cdef object __weakref__ # explicitly enable weakref for this extension type, will self-destruct when it is no longer strongly referenced.
def __add__(a, b):
return a+b
# Simple test case
def main():
total_it = 1000
for i in xrange(total_it):
for j in xrange(10000000):
ExtendedInt(j)
sys.stdout.write("\rGenerating lists of ExtendedInt : %i/%i" % (i, total_it))
如果您尝试创建大量 ExtendedInt,会发生什么情况,Python 解释器在某些时候会因 MemoryError 而崩溃。使用上面的代码 sn-p,在我的具有 4 GB 内存的机器上,它在第 11 次迭代时崩溃,但这会因机器规格而异。我尝试启用weakref,但没有解决问题。
但是,如果您将“cdef class ExtendedInt(int):”替换为“class ExtendedInt(int)”(因此它不再是扩展类型而是简单的 Python 类),那么问题就不会发生,有没有 MemoryError 崩溃。
因此,从整数继承的扩展类型似乎没有被正确释放,即使我启用了 weakref。这是我应该在跟踪器上填写的错误还是我遗漏了什么?
这是当前 Cython 版本的错误吗?我在 bugtracker 上找不到任何参考资料……或者我遗漏了一些可以解决问题的东西?
【问题讨论】:
-
你试过
cdef class ExtendedInt(cython.int):吗?你提到了它,但在你的例子中,你似乎得到了 Pythonint... -
是的,我试过了,但效果并不好。无论如何,我确认这是当前 Cython 的一个错误,感谢邮件列表。
标签: python inheritance crash cython