pythonic way to free resources

Chirayu thephoenix235 at gmx.net
Tue Aug 20 07:10:21 CEST 2002


Someone had already suggested a similar approach. However, for a case like

   class NoFile:
       def close (self): pass

   f = g = h = NoFile ()

   try:
      # stuff that opens f, g
      # some other processing which may raise an error
      # stuff that opens h
   except:
      # set some flags maybe
      raise # let the exception pass
      f.close()
      g.close()
      h.close()
   finally:
      f.close()
      g.close()
      h.close()

you end up repeating the f.close() and g.close()

Someone here suggested the Finalizer class approach avoids this with 
minimum typing.

class Finalizer:
    def close(self):
       for i in self.__dict__: i.close ()

   fin = Finalizer ()
   try:
      # f =  fin.f = open(....)
      # g =  fin.g = open(....)
      # some other processing which may raise an error
      # h =  fin.h = open(....)
   except:
      # set some flags maybe
      raise # let the exception pass
      fin.close ()
   finally:
      fin.close()

Other approaches I tried involve more typing every time i add another 
resource to the list. (I did try assigning bound methods (f.close, g.close 
and h.close in this case) instead of the objects themselves but have'nt 
found much need for the additional flexibility.


At 01:17 PM 8/20/02 +1200, Greg Ewing wrote:
>Another possibility:
>
>   class NoFile:
>     def close(self):
>       pass
>
>   f = NoFile()
>   g = NoFile()
>   h = NoFile()
>   try:
>      # stuff that opens f, g and/or h
>   finally:
>     f.close()
>     g.close()
>     h.close()





More information about the Python-list mailing list