Destructor never called ???

Tim Peters at
Fri Sep 20 03:13:52 EDT 2002

> There are several different issues.  First of all, __del__ does not get
> called if an object is destroyed by GC (GC gets used to clean up cyclic
> garbage).

If an object is destroyed by GC, and the object has a __del__, the __del__
is called.

>>> class adel:
...     def __del__(self):
...         print "I've been del'ed!"
>>> class nodel:
...     pass
>>> A = nodel()
>>> B = nodel()
>>> C = adel()
>>> A.B = B  # half of a cycle
>>> B.A = A  # the other half
>>> A.C = C  # C is not in the cycle, but ...
>>> B.C = C  # ... will become reachable only from the cycle
>>> del C    # can only get to C via the cycle now
>>> del A    # break half the cycle
>>> del B    # break the other half
>>> import gc
>>> gc.collect()  # force a collection
I've been del'ed!

What is true is that if an object *in* a trash cycle has a __del__, that
cycle will not be collected, but rather shuffled into gc.garbage for the
programmer to do something sane with it explicitly.  There may be any number
of objects with __del__s not in cycles themselves but reachable only from
cycles; they don't inhibit collection, and if collection occurs their
__del__s will be invoked.  It's only the cases where Python can't possibly
guess a safe order in which to call destructors where both __del__ and
collection are inhibited.

__del__-and-gc-go-together-like-windows-and-fork-ly y'rs  - tim

More information about the Python-list mailing list