does python have useless destructors?

Peter Hansen peter at
Thu Jun 10 15:52:41 CEST 2004

Michael Geary wrote:

> Peter Hansen wrote:
>>This code, on the other hand:
>>>    myfile = open("myfilepath", "w")
>>>    myfile.write(reallybigbuffer)
>>>    myfile.close()
>>... "feels" just right.  This is how you do it when you
>>want to be sure the file is closed, regardless of
>>other considerations like garbage collection, etc.
>>It is simple, clean, and most of all, very explicit.
> And it has a bug. :-)
> What if "myfilepath" is not writable? The open() call raises an exception,
> which jumps to the finally: block, where myfile.close() fails because myfile
> is undefined.
> What would be the cleanest way to code this to handle that error situation?

You're quite right!  Sorry... I was reacting to just the
presence or absence of the exception handling code, without
even reading it. :-(

The correct approach is of course to open the file *before*
the exception block starts.

If you are concerned that the open might fail, which is a *different*
type of exception, then you probably want a try/except block around
the whole thing as well as the try/finally.


More information about the Python-list mailing list