does python have useless destructors?
Hallvard B Furuseth
h.b.furuseth at usit.uio.no
Thu Jun 10 11:58:57 EDT 2004
Peter Hansen wrote:
>Michael Geary wrote:
>
>>>>try:
>>>> myfile = open("myfilepath", "w")
>>>> myfile.write(reallybigbuffer)
>>>>finally:
>>>> myfile.close()
>> (...)
>> And it has a bug. :-)
>(...)
>
> 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.
In that case I usually prefer 'myfile = None' before 'try'
and 'if myfile:' before close(), to avoid an extra nesting level.
BTW, another problem with calls like close() in destructors is that
exceptions from destructors are ignored (except for a warning message).
So if close() fails because the disk is full or something, your program
will happily continue as if the file was updated successfully.
class foo:
def __del__(self): raise NotImplementedError
def bar():
x = foo()
del x
print "Still happy."
bar()
-->
Exception exceptions.NotImplementedError:
<exceptions.NotImplementedError instance at 0xf30a0>
in <bound method foo.__del__
of <__main__.foo instance at 0xf3198>> ignored
Still happy.
--
Hallvard
More information about the Python-list
mailing list