pythonic way to free resources

Greg Ewing see_reply_address at something.invalid
Tue Aug 20 08:31:51 CEST 2002


Chirayu wrote:

>   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()


That's not legal Python -- you can't have except and finally
in the same try block. But in any case, you don't have to
repeat the closes:

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

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




More information about the Python-list mailing list