python - dict 不引用元素? Python2.7 改变了行为

标签 python python-2.7 reference garbage-collection python-2.x

举个例子:

>>> import gc
>>> d = { 1 : object() }
>>> gc.get_referrers(d[1])
[] # Python 2.7
[{1: <object object at 0x003A0468>}] # Python 2.5

为什么 d 没有被列为对象的引用者?

EDIT1:虽然 d 中的字典引用了对象,但为什么没有列出字典?

最佳答案

doc提到:

This function will only locate those containers which support garbage collection; extension types which do refer to other objects but do not support garbage collection will not be found.

好像字典不支持。

原因如下:

The garbage collector tries to avoid tracking simple containers which can’t be part of a cycle. In Python 2.7, this is now true for tuples and dicts containing atomic types (such as ints, strings, etc.). Transitively, a dict containing tuples of atomic types won’t be tracked either. This helps reduce the cost of each garbage collection by decreasing the number of objects to be considered and traversed by the collector.

— From What's new in Python 2.7

似乎 object() 被认为是一个原子类型,并尝试使用用户定义类的实例(即,不是 object ) 确认这一点,因为您的代码现在可以工作了。

# Python 2.7
>>> class A(object): pass
>>> r = A()
>>> d = {1: r}
>>> del r
>>> gc.get_referrers(d[1])
[{1: <__main__.A instance at 0x0000000002663708>}]

另请参阅 issue 4688 .

关于python - dict 不引用元素? Python2.7 改变了行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16857366/

相关文章:

python - 理解 Python 'with' 语句

python - 使用 XLSX Writer 将数据透视表写入 Excel 工作簿范围

python - 对包含卡住字符串的 pandas 数据框列进行过滤

java - 在 Java 中存储对单个 SecureRandom 的引用?

c++ - 如何在 C++ 中调用不同项目的方法?

Python key 错误 : '0' on printing a dictionary value

python打印转义反斜杠

python - 使用 SQLAlchemy 确定哪些列表值不在数据库列中

json - 如何修复 json.dumps 错误 '' utf 8' codec can' t 解码位置 2' 中的字节 0xe0?

java - 原始内存访问 Java/Python