import weakref
import gc
class MyClass(object):
def refer_to(self, thing):
self.refers_to = thing
foo = MyClass()
bar = MyClass()
foo.refer_to(bar)
bar.refer_to(foo)
foo_ref = weakref.ref(foo)
bar_ref = weakref.ref(bar)
del foo
del bar
gc.collect()
print foo_ref()
我希望您将
foo_ref
和bar_ref
分别与foo
和bar
保持弱引用,只要它们相互引用 *,但实际上打印的是None
. 我该如何防止垃圾回收器收集引用循环中的某些对象?在这段代码中,
bar
应该被垃圾回收,因为它不再是foo
-bar
引用循环的一部分。baz = MyClass()
baz.refer_to(foo)
foo.refer_to(baz)
gc.collect()
* 我知道防止循环引用被垃圾回收可能看起来毫无意义,但我的使用场景需要这样做。我有一堆对象以网状方式相互引用,并且还有一个WeakValueDictionary
,它在这一堆对象中保留对每个对象的弱引用。我只希望当一个对象孤立无援时,也就是没有其他对象在这一堆中引用它时,才将其进行垃圾回收。
__del__
,而CPython则明确选择不这样做。我不知道PyPy已经做出了这个选择。 :-) - Martijn Pieters