gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:23:50 27 4
gpt4 key购买 nike

举个例子:

>>> 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com