[Python-ideas] breaking cycles that include __del__

Nick Coghlan ncoghlan at gmail.com
Mon Oct 19 22:30:05 CEST 2009

Daniel Stutzbach wrote:
> On Sat, Oct 17, 2009 at 11:17 AM, Nick Coghlan <ncoghlan at gmail.com
> <mailto:ncoghlan at gmail.com>> wrote:
>     The gist is that you split your object into a "core" which requires
>     finalisation (but can never itself be caught up in a cycle) and the main
>     object which may participate in cycles. A weak reference to the main
>     object is placed in a global container. When the weak reference callback
>     is invoked, the object core is still in a valid state so it can be
>     finalised safely, even though the main object may be in the midst of
>     cycle collection.
>     This recipe gives a pretty good idea of how that approach works:
>     http://code.activestate.com/recipes/519610/
> That idiom (and that recipe in particular! yuck!) is pretty convoluted, IMO.

True, but as Adam pointed out, something along those lines is necessary
to avoid accessing already destroyed objects in __del__ methods.

My point was mainly that the idiom works, we know it works, we just
don't have a particularly nice way of spelling it. (Even I thought that
recipe was fairly ugly - I just linked it because it does a good job of
explaining the requirements of the technique)

For the diagnostic task you're talking about, wouldn't it be better to
create your own collection of weakrefs to instances of the class you're
interested in, checking that the object has been closed in the callback
and then iterate over that collection in an atexit handler?

You wouldn't have any __del__ methods of your own interfering with
garbage collection then and the atexit handler would be a final
diagnostic to check if the objects were getting caught up in cycles with
*other* objects with __del__ methods.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list