__del__ problem - would adopting Garbage Collection fix this?

Neil Schemenauer nascheme at enme.ucalgary.ca
Thu Apr 20 00:50:09 EDT 2000

Greg Ewing <greg at cosc.canterbury.ac.nz> wrote:
>By the way, does anyone know what the recently
>announced GC patch does about __del__ methods?

Well, I guess I should. :)

When garbage is found by the collector (ie. reference cycles not
reachable from Python), all objects reachable from __del__
methods are moved into a separate set.  This is what I call
uncollectable garbage.  Uncollectable instances are currently
added to a global list of uncollectable objects reachable from
within Python.  If the programmer creates such garbage it is up
to them to deal with it.

The bottom line is don't add __del__ methods to objects that form
cycles.  It is, however, okay to reference objects with __del__
methods from objects involved in reference cycles.  If that's not
clear perhaps an example will help:

    >>> import gc
    >>> class A:
    ...     pass
    >>> class B:
    ...     def __del__(self):
    ...         pass
    >>> a = A()
    >>> a.b = B() # referenced from, not involved in cycle
    >>> c = A()
    >>> a.c = c
    >>> c.a = a
    >>> del a, c # collectable garbage created
    >>> gc.collect()
    gc: collectable <Object 0x81c6a24>
    gc: collectable <A instance at 81c6a04>
    gc: collectable <Object 0x81c699c>
    gc: collectable <A instance at 81c697c>
    >>> a = A()
    >>> b = B()
    >>> a.b = b
    >>> b.a = a
    >>> del a, b # uncollectable garbage created
    >>> gc.collect()
    gc: uncollectable <Object 0x81c351c>
    gc: uncollectable <A instance at 81abbc4>
    gc: uncollectable <Object 0x81abbe4>
    gc: uncollectable <B instance at 81c50a4>
    >>> gc.garbage
    [<__main__.A instance at 81abbc4>, <__main__.B instance at

There was quite a bit of discussion about this issue on the
python-dev list.

Getting back on topic, GC does not help with this problem.  In
fact it is hard to make __del__ methods behave sanely with GC.
Nice __del__ semantics are one of the benefits of reference
counting.  __del__ methods are strong medicine, use them


"A language that doesn't affect the way you think about programming, is
not worth knowing" -- Alan Perlis

More information about the Python-list mailing list