Cleaning up after failing to contructing objects

Shai shai at
Wed Jul 15 18:45:57 EDT 2009

Since nobody else mentioned this...

Python classes have a magic method called __del__ which is usually
called just before an object is garbage-collected. Further, Python
uses reference-counting to tell when an object is no longer
accessible. This means that if your resource classes define __del__
methods, these will be called properly when the object using them is
destroyed, and you don't need to write an explicit close() method for

class Resource(object):
  def __init__(self, param):
    # acquire resource

  def __del__(self):
    # release resource

not_my_responsibility = Resource(1)

class Foo(object):
  def __init__(self):
     self.ref = not_my_responsibility # self.ref.__del__() will not be
called as long as the module exists
     local = Resource(2) # local.__del__() will be called as soon as
__init__ is exited
     self.held = Resource(3) # self.held.__del__() will be called when
the object dies
     z = 1/0 # The exception in the initializer will kill the object,
triggering some Resource.__del__() calls

There are two caveats:

1) __del__ methods prevent instances of your class from being
collected when they are involved in cyclical structures; this means if
your structures start to get complex (sometimes a doubly-linked list
is complex enough), you may find yourself leaking memory.

2) The bit about reference counting, which allows predictable
destruction, holds for CPython, but not for Jython, and IIRC also not
for IronPython (I don't know about PyPy or other implementations). It
is a feature of the reference implementation, not the language

More information about the Python-list mailing list