does python have useless destructors?

Hallvard B Furuseth h.b.furuseth at
Thu Jun 10 17:58:57 CEST 2004

Peter Hansen wrote:
>Michael Geary wrote:
>>>>    myfile = open("myfilepath", "w")
>>>>    myfile.write(reallybigbuffer)
>>>>    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."
  Exception exceptions.NotImplementedError:
    <exceptions.NotImplementedError instance at 0xf30a0> 
    in <bound method foo.__del__
    of < instance at 0xf3198>> ignored
  Still happy.


More information about the Python-list mailing list