Exceptions and Object Destruction

MRAB python at mrabarnett.plus.com
Fri Jun 12 21:26:50 EDT 2009


Nikolaus Rath wrote:
> Nikolaus Rath <Nikolaus at rath.org> writes:
>> Hi,
>>
>> Please consider this example:
> [....]
> 
> I think I managed to narrow down the problem a bit. It seems that when
> a function returns normally, its local variables are immediately
> destroyed. However, if the function is left due to an exception, the
> local variables remain alive:
> 
> ---------snip---------
> #!/usr/bin/env python
> import gc
> 
> class testclass(object):
>     def __init__(self):
>         print "Initializing"
>         
>     def __del__(self):
>         print "Destructing"
>             
> def dostuff(fail):
>     obj = testclass()
> 
>     if fail:
>         raise TypeError
>     
> print "Calling dostuff"
> dostuff(fail=False)
> print "dostuff returned"
> 
> try:
>     print "Calling dostuff"
>     dostuff(fail=True)
> except TypeError:
>     pass
> 
> gc.collect()
> print "dostuff returned"    
> ---------snip---------
> 
> 
> Prints out:
> 
> 
> ---------snip---------
> Calling dostuff
> Initializing
> Destructing
> dostuff returned
> Calling dostuff
> Initializing
> dostuff returned
> Destructing
> ---------snip---------
> 
> 
> Is there a way to have the obj variable (that is created in dostuff())
> destroyed earlier than at the end of the program? As you can see, I
> already tried to explicitly call the garbage collector, but this does
> not help.
> 
Are the objects retained because there's a reference to the stack
frame(s) in the traceback?



More information about the Python-list mailing list