Cleaning up after failing to contructing objects

Scott David Daniels Scott.Daniels at Acm.Org
Mon Jul 6 23:15:44 CEST 2009

brasse wrote:
> I have been thinking about how write exception safe constructors in
> Python. By exception safe I mean a constructor that does not leak
> resources when an exception is raised within it. 
 > As you can see this is less than straight forward. Is there some kind
 > of best practice that I'm not aware of?

Not so tough.  Something like this tweaked version of your example:

class Foo(object):
     def __init__(self, name, fail=False): = name
         if not fail:
             print '%s.__init__(%s)' % (type(self).__name__, name)
             print '%s.__init__(%s), FAIL' % (type(self).__name__, name)
             raise ValueError('Asked to fail: %r' % fail)

     def close(self):
         print '%s.close(%s)' % (type(self).__name__,

class Bar(object):
     def __init__(self):
         unwind = []
             self.a = Foo('a')
             self.b = Foo('b', fail=True)
         except Exception, why:
             while unwind):

bar = Bar()

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list