does python have useless destructors?
"Martin v. Löwis"
martin at v.loewis.de
Sun Jun 13 12:01:11 CEST 2004
Michael P. Soulier wrote:
> As soon as I heard about not being able to trust destructors, I was
> shocked, because I do rely on guaranteed finalization, and I also
> consider it to be very elegant.
"Guarantee" and "able to rely on" are different things, actually.
A guarantee is something that someone gives you, which they might
not do even though they could. For example, you can rely on sunset
to occur before midnight, but nobody might give you a guarantee for
So the Python language specification does not guarantee anything about
invoking __del__. However, you can still rely on C-Python 2.3.4
invoking it eventually. More precisely, C-Python 2.3.4 (and most other
releases of C-Python) will invoke __del__ if the last reference to
an object goes away. A reference goes away if:
- the variable is del'ed, or a different value is assigned, or
- the variable is a local variable, and the function terminates
through a return (if the function terminates through an exception,
a traceback object is constructed which takes over the local
- the variable is attribute of an object, and the object goes away
- the variable is an implicit variable in the interpreter, and
gets a new value. Some of the implicit variables are:
- the current exception and traceback
- the last exception and traceback
- the sys module
- the codecs module
> myfile = open("myfilepath", "w")
> If the write fails due to a lack of disk space, the exception will
> prevent the explicit close() from happening. Now, if myfile goes out of
> scope, I would hope that the file object is destroyed and thus the file
> is closed, but after reading the python documentation, it seems that
> the only way to guarantee closure of the file is using the mentioned
> try/finally construct...
C-Python 2.3.4 will close the fil if myfile goes out of scope, unless
there is an exception, in which case myfile is referred to in the
traceback, in which case the file is closed when the traceback object
is released, which happens when the exception handler for the exception
has completed. If the exception was put out through PyErr_Print, the
object stays alive through sys.last_traceback, where it stays until
the next exception occurs.
More information about the Python-list