Hello! 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. The following is an example of one possible way to do it:
class Foo(object): def __init__(self, name, fail=False): self.name = name if not fail: print '%s.__init__(%s)' % (self.__class__.__name__, self.name) else: print '%s.__init__(%s), FAIL' % (self.__class__.__name__, self.name) raise Exception() def close(self): print '%s.close(%s)' % (self.__class__.__name__, self.name) class Bar(object): def __init__(self): try: self.a = Foo('a') self.b = Foo('b', fail=True) except: self.close() def close(self): if hasattr(self, 'a'): self.a.close() if hasattr(self, 'b'): self.b.close() bar = Bar() As you can see this is less than straight forward. Is there some kind of best practice that I'm not aware of? :.:: mattias -- http://mail.python.org/mailman/listinfo/python-list