On Oct 19, 4:14 pm, Grant Edwards <inva...@invalid.invalid> wrote: > On 2009-10-19, arve.knud...@gmail.com <arve.knud...@gmail.com> wrote: > > > I thought that file objects were supposed to be > > garbage-collected and automatically closed once they go out of > > scope, > > At some point after they go out of scope, they will be. > Eventually. Exactly when is an implementation detail. > > > 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, > > If your program relies on the assumption that some particular > object will be garbage-collected between points A and B, then > that's a bug in your program. If you depend on the fact that > some object has been delted, then "del" it. If you depend on > the fact that a file is closed, then close it.
Personally I am against that assumption, and prefer a utility function which reads the file and automatically closes it in a "finally" block (in lieu of the "with" keyword). However, when providing a patch for a high-profile opensource Python project I was scolded for going to such lengths, as the prescribed style was to just open files and let them be closed implicitly. Also, the problem may arise when I call a function in a 3rd party library, that it opens files which I then can't delete upon an exception from within said function. Actually, something like that did happen and spurred my original question, but fortunately a reference to the file was kept in the 3rd party object I was operating on, so I was able to free it in a "finally" block. Arve -- http://mail.python.org/mailman/listinfo/python-list