File not closed on exception

Ethan Furman ethan at stoneleaf.us
Tue Oct 20 09:52:15 EDT 2009


arve.knudsen at gmail.com wrote:
> On Oct 19, 3:48 pm, Ethan Furman <et... at stoneleaf.us> wrote:
> 
>>arve.knud... at gmail.com wrote:
>>
>>>Hi
>>
>>>I thought that file objects were supposed to be garbage-collected and
>>>automatically closed once they go out of scope, at least that's what
>>>I've been told by more merited Python programmers. I'm also quite sure
>>>that this is quite a common assumption in various programs, at least
>>>given what opensource code I've seen in my time. However, the
>>>following script doesn't work on Windows, since the file is still open
>>>when I try to remove it:
>>
>>>import os.path
>>
>>>def create():
>>>    f = file("tmp", "w")
>>>    raise Exception
>>
>>>try: create()
>>>finally:
>>>    os.remove("tmp")
>>
>>>So, what's the deal exactly, is the file supposed to be garbage-
>>>collected (and closed) at the end of create?
>>
>>>Thanks!
>>>Arve
>>
>>When an exception is raised, the entire stack frame at that location
>>(which includes local vars) is saved in the exception traceback.  Since
>>the objects are still alive, they are not GC'ed.  That is why this is
>>better:
>>
>>def create():
>>     f = file("tmp", "w")
>>     try:
>>         do_stuff_that_raises_exception
>>     finally:
>>         os.remove("tmp")
>>
>>~Ethan~
> 
> 
> Why should this work? If I replace "do_stuff_that_raises_exception"
> with "raise Exception", it fails in the same way, since the file is
> open. Maybe you forgot "f.close()"? In any case, thanks for explaining
> that the traceback keeps the object alive, that explains the issue.
> 
> Arve

Indeed.  That should have been f.close() in the finally block.  My 
apologies.

~Ethan~



More information about the Python-list mailing list