[Python-ideas] breaking cycles that include __del__

Nick Coghlan ncoghlan at gmail.com
Sat Oct 17 18:17:03 CEST 2009


Daniel Stutzbach wrote:
> It would be simple to implement, efficient, and the cognitive load for
> the programmer using __del__ and __clear__ is small.

I believe it would be better to find ways to streamline the existing
"collectible-yet-finalised" mechanism using weak references rather than
adding another way to do it.

Although even before that, just documenting how weakrefs can be used
instead of __del__ in the weakref module docs and crosslinking to that
from the __del__ method documentation would be an improvement on the
status quo.

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/

Cheers,
Nick.

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



More information about the Python-ideas mailing list