Destructors and exceptions

David Turner dkturner at
Tue Jun 8 11:44:04 CEST 2004


> There is no Python equivalent of C++'s "destructor garanteed to be called
> upon scope exit", for a couple of reasons: scope exit only destroys
> references to objects, not the objects themselves; destruction of objects is
> left to the garbage collector and you have no influence on it. In
> particular, the gc is not required to release resources, so finalizers (the
> __del__ method, closest to C++'s destructor) may not get called. This means
> __del__ is pretty much useless (AFAIMC), and you can't rely on them being
> called before program exit (or ever, for that matter).

In the documentation for the "gc" module, it states that objects with
a __del__ method are not subject to garbage collection; they are
collected using reference counting.  Which means that one can rely on
locals (to which there is only one reference) being destroyed in a
predictable fashion -- but there's an exception.  Section 3.1 of the
Python Reference Manual specifies that raising exceptions may keep
objects alive.  What I take this to mean from an implementation point
of view is that the exception mechanism doesn't unwind scope. 
Therefore, the destruction of locals in the presence of an exception
is deferred to global clean-up time when the program exits.

I can't think of any technical objections to having the exception
mechanism also release references to locals that are going to go out
of scope (unless one was planning to support resuming).  Can you?

David Turner

More information about the Python-list mailing list