Re: Bug or feature?

Guido.van.Rossum@cwi.nl
Mon, 29 Aug 1994 11:45:49 +0200

> I am creating a class which uses __init__ and __del__ methods. The
> __init__ method has a try/except construct. The problem is, whenever
> the except clause in __init__ is executed, then the __del__ method
> is not called upon destruction of the object. Is this a bug or a
> feature? The functionality is the same on the 32-bit DOS version
> 1.0.2 as well as the QNX version 1.0.0 I built from the sources. If
> this is a bug, here is a module which shows the problem:
>
> class test:
> def __init__ (self, arg):
> try:
> self.attr = 1 / arg
> print 'Success'
> except:
> print 'Exception'
>
> def __del__ (self):
> print 'Delete'

Erm, this is an unfortunate effect of a feature of try/except. When
an exception is caught in an except clause (not when it is raised, nor
when the try statement has no matching except clause, not for
try/finally statements), info about the exception is stored in the
three variables sys.exc_type, sys.exc_value and sys.exc_traceback.
The latter contains a stack backtrace, inspectable with pdb for
instance. This includes references to the dictionaries of local
variables of the functions in the backtrace -- which means that a
reference to 'self' is lingering somewhere.

Usually a good way to get rid of this reference is to assign None to
sys.exc_traceback, either in each except clause, or (often easier) at
the points where you want garbage collection to occur.

Note that an interactive interpreter has another similar magic
variable: the info printed for an *unhandled* exception is stored in
sys.last_{type,value,traceback}.

It has been suggested that sys.exc_* should only be made available
*inside* the except clause. Unfortunately that would require the
"compiler" to add cleanup code (essentially a hidden try/finally
statement) to each except clause -- once the interpreter has entered
the except clause it doesn't know any more that it is inside an except
handler. I'd rather not mess with that part of the language.

This *is* documented (though feebly) in the documentation for the sys
module.

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>