does python have useless destructors?
Peter Hansen
peter at engcorp.com
Thu Jun 10 09:52:41 EDT 2004
Michael Geary wrote:
> Peter Hansen wrote:
>>This code, on the other hand:
>>
>>>try:
>>> myfile = open("myfilepath", "w")
>>> myfile.write(reallybigbuffer)
>>>finally:
>>> 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.
-Peter
More information about the Python-list
mailing list