[Python-3000] Removing __del__
Greg Ewing
greg.ewing at canterbury.ac.nz
Wed Sep 27 02:36:14 CEST 2006
Marcin 'Qrczak' Kowalczyk wrote:
> "It's a feature of Python's weakrefs too that when a weakref goes
> away, the callback (if any) associated with it is thrown away too,
> unexecuted."
>
> I disagree with this choice. Doesn't it prevent weakrefs to be used as
> finalizers?
No, it's quite possible to build a finalization mechanism
on top of weakrefs.
To register a finalizer F for an object O, you create a
weak reference W to O and store it in a global list.
You give W a callback that invokes F and then removes
W from the global list.
Now there's no way that W can go away before its callback
is invoked, since that's the only thing that removes it
from the global list.
Furthermore, if the user makes a mistake and registers
a function F that references its own object O, directly
or indirectly, then eventually we will be left with a
cycle that's only being kept alive from the global list
via W and its callback. The cyclic GC can detect this
situation and move the cycle to a garbage list or
otherwise alert the user.
I don't believe that this mechanism would be any
harder to use *correctly* than __del__ methods
currently are, and mistakes made in using it would
be no harder to debug.
--
Greg
More information about the Python-3000
mailing list