pythonic way to free resources

Chirayu thephoenix235 at gmx.net
Sat Aug 17 06:25:28 CEST 2002


this one is nice (by Bengt Richter). but we usually want to handle just one 
or two exception types and let the others pass. might the following work?

     class Finalizer:
         def finalize(self):
             for f in self.__dict__.values():
                 f.close()
         def __del__ (self): self.finalize()

     fin = Finalizer()
     try:
         fin.f1 = f1 = file(...)
         # do stuff with f1
         fin.f2 = f2 = file(...)
         # do stuff with f2
     except IOError, e:
          print "An IO Error prevented success: %s." % e
          if we_need_to_return_here:
              del f
              return
     except Exception, e:
          del f
          raise
     # release all resources successfully allocated and logged
     del f

i guess this sprinkles the code with "del f" (or "f.finalize()") but it 
still looks a lot better than not using a Finalizer class.

or perhaps, with nested try blocks.

     fin = Finalizer()
     try:
         try:
             fin.f1 = f1 = file(...)
             # do stuff with f1
             fin.f2 = f2 = file(...)
             # do stuff with f2
         except IOError, e:
              print "An IO Error prevented success: %s." % e
              if we_need_to_return_here:
                  return
         except Exception, e:
              raise
     finally:
        # release all resources successfully allocated and logged
        del f

ps: would the "del f" would have the possibly minor advantage of 
decrementing the ref counts (or deleting) of all the objects it holds?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20020817/a3d76d67/attachment.html>


More information about the Python-list mailing list