WeakValueDictionary保留对对象的引用,不再有更强的引用 [英] WeakValueDictionary retaining reference to object with no more strong references

查看:79
本文介绍了WeakValueDictionary保留对对象的引用,不再有更强的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> from weakref import WeakValueDictionary
>>> class Foo(object):
...     pass
>>> foo = Foo()
>>> db = WeakValueDictionary()
>>> db['foo-id'] = foo
>>> del foo
>>> dict(db)
{'foo-id': <__main__.Foo object at 0x4dd946c>}

为什么它显示此内容而不是空字典?请注意,此代码会产生我期望的结果:

Why does it show this instead of an empty dictionary? Note that this code produces the result I'd expect:

>>> db2 = WeakValueDictionary()
>>> db2['disposable-id'] = Foo()
>>> dict(db2)
{}

在执行脚本(而不是交互式解释器)时,它的行为也符合预期:

It also behaves as expected when executing a script (instead of the interactive interpreter):

from weakref import WeakValueDictionary
class Foo(object):
    pass
foo = Foo()
db = WeakValueDictionary()
db['foo-id'] = foo
del foo
print str(dict(foo))
# prints {}

推荐答案

WeakValueDictionary不保证没有正常引用时,将删除条目.它保证的是它不会在适当的时候阻止垃圾收集-您的对象是可收集垃圾,而不是收集垃圾.发生垃圾收集时,该条目将消失.

WeakValueDictionary does not guarantee that entries will be removed when there are no normal references. What it guarantees is that it will not prevent garbage collection in due course - your object is garbage collectable, not garbage collected. The entry will disappear when garbage collection happens.

这篇关于WeakValueDictionary保留对对象的引用,不再有更强的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆