File not closed on exception

arve.knudsen at arve.knudsen at
Tue Oct 20 08:23:49 CEST 2009

On Oct 19, 5:56 pm, "Gabriel Genellina" <gagsl-... at>
> En Mon, 19 Oct 2009 09:45:49 -0200, arve.knud... at  
> <arve.knud... at> escribió:
> > 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.
> An object (any object) is destroyed as soon as the last reference to the  
> it is removed. A local variable holds a reference to the file object; it  
> that is the ONLY reference, the file object will be destroyed when the  
> variable goes out of scope, yes.
> Note that:
> - there might be more references to the object
> - garbage collection is a separate subject; objects are reference-counted,  
> zero=>kaputt, the GC has no say on this. GC is only used to break cycles  
> (a->b, b->a) that would prevent the objects to reach 0 references.
> - this behavior is specific of CPython
> > 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.
> When an object holds references to external resources that must be freed,  
> this is not a good idea. Being explicit with the resource deallocation is  
> much better than relying on object destruction sometime in the future...

I agree, but like I said, I've been told that this (implicit closing
of files) is the correct style by more merited Python developers, so
that made me think I was probably wrong ..


More information about the Python-list mailing list