Destructors and exceptions

Humpty Dumpty oliver.schoenborn at
Tue Jun 8 05:34:08 CEST 2004

"David Turner" <dkturner at> wrote in message
news:e251b7ba.0406070651.1c98c09d at

> The problem is that when an exception is raised, the destruction of
> locals appears to be deferred to program exit.  Am I missing
> something?  Is this behaviour by design?  If so, is there any reason
> for it?  The only rationale I can think of is to speed up exception
> handling; but as this approach breaks many safe programming idioms, I
> see it as a poor trade.

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).

I agree, it is a real pitty that Python doesn't have a way of doing what you
mention, other than try-finally, which makes code more difficult to read. A
new specifier, e.g. "scoped", would be a required addtion to Python:
interpreter would garantee that __del__ of scoped objects would be called on
scope exit, and raise an exception if attempt to alias.


More information about the Python-list mailing list