does python have useless destructors?
Hallvard B Furuseth
h.b.furuseth at usit.uio.no
Thu Jun 10 17:58:57 CEST 2004
Peter Hansen wrote:
>Michael Geary wrote:
>>>> myfile = open("myfilepath", "w")
>> 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.
def __del__(self): raise NotImplementedError
x = foo()
print "Still happy."
<exceptions.NotImplementedError instance at 0xf30a0>
in <bound method foo.__del__
of <__main__.foo instance at 0xf3198>> ignored
More information about the Python-list