does python have useless destructors?

Peter Hansen peter at engcorp.com
Fri Jun 11 15:27:14 EDT 2004


Tim Bradshaw wrote:

> "Delaney, Timothy C (Timothy)" <tdelaney at avaya.com> wrote in message news:<mailman.780.1086840001.6949.python-list at python.org>...
> 
> 
>>myfile = open("myfilepath", "w")
>>
>>try:
>>    myfile.write(reallybigbuffer)
>>finally:
>>    myfile.close()
> 
> I don't think this is save.  Is it certain that there can be no
> problem between the open and the try?  

Yes, it's certain to be safe (barring multithreaded stuff
rebinding 'myfile' in between, which is irrelevant to the
discussion).  Are you perhaps concerned that the open itself
might fail?  If so, it needs its own try/except block, as I
noted elsewhere.  The finally is only need *if* the open
succeeds, but unless you insert code between open() and
'try', it's safe.

-Peter



More information about the Python-list mailing list