does python have useless destructors?

Tim Peters tim.one at comcast.net
Fri Jun 11 15:50:34 EDT 2004


[Delaney, Timothy C]
>>> myfile = open("myfilepath", "w")
>>>
>>> try:
>>>    myfile.write(reallybigbuffer)
>>> finally:
>>>    myfile.close()

[Tim Bradshaw]
>> I don't think this is save.  Is it certain that there can be no problem
>> between the open and the try?

[Peter Hansen]
> 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.

Believe it or not, it isn't entirely "safe", but for a different reason:
it's quite possible for, e.g., KeyboardInterrupt to get raised and processed
between the "finally:" and the "myfile.close()" -- Google on

    "safe asynchronous exceptions for python"

for a good paper on the topic.






More information about the Python-list mailing list