Cleaning up after failing to contructing objects
Scott David Daniels
Scott.Daniels at Acm.Org
Mon Jul 6 17:15:44 EDT 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):
self.name = name
if not fail:
print '%s.__init__(%s)' % (type(self).__name__, name)
else:
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__, self.name)
class Bar(object):
def __init__(self):
unwind = []
try:
self.a = Foo('a')
unwind.append(a)
self.b = Foo('b', fail=True)
unwind.append(b)
...
except Exception, why:
while unwind):
unwind.pop().close()
raise
bar = Bar()
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list