Q on explicitly calling file.close

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Sep 6 05:56:34 CEST 2009

On Sun, 06 Sep 2009 01:51:50 +0000, kj wrote:

> In <02b2e6ca$0$17565$c3e8da3 at news.astraweb.com> Steven D'Aprano
> <steve at REMOVE-THIS-cybersource.com.au> writes:
>>(3) For quick and dirty scripts, or programs that only use one or two
>>files, relying on the VM to close the file is sufficient (although lazy
>>in my opinion *wink*)
> It's not a matter of laziness or industriousness, but rather of code
> readability.  The real problem here is not the close() per se, but
> rather all the additional machinery required to ensure that the close
> happens.  When the code is working with multiple file handles
> simultaneously, one ends up with a thicket of try/finally's that makes
> the code just *nasty* to look at.

Yep, that's because dealing with the myriad of things that *might* (but 
probably won't) go wrong when dealing with files is *horrible*. Real 
world code is almost always much nastier than the nice elegant algorithms 
we hope for.

Most people know they have to deal with errors when opening files. The 
best programmers deal with errors when writing to files. But only a few 
of the most pedantic coders even attempt to deal with errors when 
*closing* the file. Yes, closing the file can fail. What are you going to 
do about it? At the least, you should notify the user, then continue. 
Dying with an uncaught exception in the middle of processing millions of 
records is Not Cool. But close failures are so rare that we just hope 
we'll never experience one.

It really boils down to this... do you want to write correct code, or 
elegant code?


More information about the Python-list mailing list