[Python-3000] Removing __del__
Nick Coghlan
ncoghlan at gmail.com
Wed Sep 27 03:36:15 CEST 2006
Greg Ewing wrote:
>>> # Use closure to get at weakref to allow direct invocation
>>> # This creates a cycle, so this approach relies on cyclic GC
>>> # to clean up the finalizer objects!
>
> This implementation is broken. There's no need
> to create any such cycle.
I know, but it was late and my brain wasn't up to the job of getting rid of it :)
Here's a pretty easy way to fix it to avoid relying on the cyclic GC (actually
based on your other message about explicitly breaking the cycle when the
finalizer is invoked):
_finalizer_refs = set()
def finalizer(*args, **kwds):
"""Create a finalizer from an object, callback and keyword dictionary"""
# Use positional args and a closure to avoid namespace collisions
obj, callback = args
def _finalizer(_ref=None):
"""Callable that invokes the finalization callback"""
# Use closure to get at weakref to allow direct invocation
try:
ref = boxed_ref.pop()
except IndexError:
pass
else:
_finalizer_refs.remove(ref)
callback(_finalizer)
# Give callback access to keyword arguments
_finalizer.__dict__ = kwds
boxed_ref = [weakref.ref(obj, _finalizer)]
_finalizer_refs.add(boxed_ref[0])
return _finalizer
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://www.boredomandlaziness.org
More information about the Python-3000
mailing list