Cleaning up after failing to contructing objects

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jul 6 19:49:40 EDT 2009


En Mon, 06 Jul 2009 18:15:44 -0300, Scott David Daniels  
<Scott.Daniels at acm.org> escribió:

> 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:

Another variant: Presumably, there is already a method in Bar responsible  
for "normal" cleanup; just make sure it gets called (and write it in a  
robust way):

> 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):
     a = None # default values
     b = None

     def __init__(self):
         try:
             self.a = Foo('a')
             self.b = Foo('b', fail=True)
         except Exception, why:
             self.cleanup()
             raise

     def cleanup(self):
         if self.a is not None:
             self.a.close()
         if self.b is not None:
             self.b.close()

bar = Bar()

-- 
Gabriel Genellina




More information about the Python-list mailing list