Cleaning up after failing to contructing objects

brasse thebrasse at gmail.com
Mon Jul 6 16:36:59 EDT 2009


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



More information about the Python-list mailing list