does python have useless destructors?

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Wed Jun 9 23:59:52 EDT 2004


Michael Geary wrote:

>>> 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? 

myfile = open("myfilepath", "w")

try:
    myfile.write(reallybigbuffer)
finally:
    myfile.close()

Tim Delaney




More information about the Python-list mailing list