Resolve circular reference

Hrvoje Niksic hniksic at xemacs.org
Fri Jan 14 06:25:11 EST 2011


Magnus Lyckå <lycka at carmen.se> writes:

>>>> a = X()
>>>> del a
> Deleted <__main__.X instance at 0x00CCCF80>
>>>> a=X()
>>>> b=X()
>>>> a.b=b
>>>> b.a=a
>>>> del a
>>>> gc.collect()
> 0
>>>> del b
>>>> gc.collect()
> 4

If your method has a __del__ at all, the automatic cyclic collector is
disabled.  It detects the cycle, but it only stores the objects in
gc.garbage, to give you a chance to do something about them, such as
break the cycle(s) yourself.  For example:

>>> class X(object):
...   def __del__(self):
...     print 'deleted', self
...
>>> a, b = X(), X()
>>> a.cycle = b
>>> b.cycle = a
>>> del a, b
>>> import gc
>>> gc.collect()
4
>>> gc.garbage
[<__main__.X object at 0xb76d84cc>, <__main__.X object at 0xb76d980c>]
>>> del gc.garbage[0].cycle
>>> del gc.garbage[:]
deleted <__main__.X object at 0xb76d980c>
deleted <__main__.X object at 0xb76d84cc>



More information about the Python-list mailing list