[Python-3000] Removing __del__
Marcin 'Qrczak' Kowalczyk
qrczak at knm.org.pl
Tue Sep 19 16:33:52 CEST 2006
Michael Chermside <mcherm at mcherm.com> writes:
> Adam Olsen:
>> I agree here. I think an executor approach is much better; kill the
>> object, then make a weakref callback do any further cleanups using
>> copies it made in advance.
I agree. Objects with finalizers with the semantics of __del__ are
inherently unsafe: they can be finalized when they are still in use,
namely when they are used by a finalizer of another object.
The correct way is to register a finalizer from outside the object,
such that it's invoked asynchronously when the associated object has
been garbage collected. Everything reachable from a finalizer is
As far as I understand it, Python's weakref have a mostly correct
Finalizers must be invoked from a separate thread:
The finalizer should not access the associated object itself (or it
will never be invoked), but it should only access the parts of the
object and other objects that it needs.
Sometimes it is necessary to split an object into an outer part which
triggers finalization, and an inner part which is accessed by the
finalizer. Even though this looks inconvenient, this design is
necessary for building rock solid finalizable objects.
This design allows for the presence of a finalizer to be a private
implementation detail. __del__ methods don't have this property
because objects with finalizers are unsafe to use from other
Python documentation contains the following snippet:
"Starting with version 1.5, Python guarantees that globals whose name
begins with a single underscore are deleted from their module before
other globals are deleted; if no other references to such globals
exist, this may help in assuring that imported modules are still
available at the time when the __del__() method is called."
This is clearly a hack which just increases the likelihood that the
code works. A correct design allows to make code which works in 100%
of the cases.
__("< Marcin Kowalczyk
\__/ qrczak at knm.org.pl
More information about the Python-3000