cleanup after exceptions

Padraig at Linux.ie Padraig at Linux.ie
Thu Dec 18 15:09:02 EST 2003


Jp Calderone wrote:
> On Thu, Dec 18, 2003 at 07:11:12PM +0000, Padraig at Linux.ie wrote:
> 
>>Hi,
>>
>>I'm a little confused why objects
>>are not deleted after they go
>>out of scope due to an exception?
> 
> 
>   Because objects don't go out of scope.  Only variables do.  Objects remain
> "alive" as long as there are any references to them.
> 
> 
>>For e.g.
>>
>>
>>>>>import time
>>>>>
>>>>>def f():
>>>>>    myfile=open("file.test","w")
>>>>>    myfile.write("not flushed\n")
>>>>>    exception=throw
>>>>>
>>>>>f()
>>>>>time.sleep(10)
>>
>>
>>The file is not written/closed until
>>the python interpreter exits.
>>The same thing applies to other objects.
> 
> 
>   In this case, the traceback still holds a reference to the frame from
> which the exception was raised,

OK I can see that, but why doesn't a pass on the exception release it?
This is demonstrated with:

#!/usr/bin/env python

import time

class c:
     def __del__(self):
         print "del"

def f():
     C=c()
     exception=throw

try:
     f()
except:
     pass

time.sleep(3)


> which itself holds a reference to all the
> locales from that function.

don't know what you mean by this

> 
>   Calling sys.exc_clear()

This isn't in version 2.2.2 at least

> (possibly followed by gc.collect()) should force
> the cleanup you expect.

thanks,
Pádraig.





More information about the Python-list mailing list