[Python-ideas] breaking cycles that include __del__

Antoine Pitrou solipsis at pitrou.net
Wed Oct 21 00:34:15 CEST 2009

Scott Dial <scott+python-ideas at ...> writes:
> This is made clear in the gcmodule.c comments, but is severely lacking
> from the actual documentation in the weakref module. But also, Antoine's
> is flawed in the same manner.

You're right, I've been too quick in posting this.
The following works, however:

import weakref, gc
class Foo:
    _w = {}
    def __init__(self):
        k = id(self)  
        def not_closed(_, d=Foo._w, k=k, r=repr(self)):
            del d[k]
            print ("%s not closed!" % r)
        Foo._w[k] = weakref.ref(self, not_closed)

    def close(self):
        # Close...
        # and then destroy weakref
        Foo._w.pop(id(self), None)

x,y = Foo(), Foo()
x.y, y.x = y, x
del x
del y



More information about the Python-ideas mailing list