Abstracting try..finally with generators (instead of macros)

Andrew Dalke adalke at mindspring.com
Sun Dec 15 01:10:46 EST 2002


Beni Cherniavsky:
 > I believe I've just discovered a new cool use for generators, one that
 > people thought they need macros for [1].

Cool thought.  Though you could also have done

import sys
class withmyout_safe3:
   def __init__(self, handle):
     self.flg = 0
     self.saved = sys.stdout
     sys.stdout = handle
   def __getitem__(self, n):
     if self.flg:
       raise IndexError
     self.flg = 1
   def __del__(self, sys = sys):
     # Need a reference to 'sys' (I think) in case this is a variable
     # in module scope and the sys module gets cleared before the module
     # containing the variable.  OTOH, I think sys is one of the ones
     # which may be guaranteed to clean up last?
     sys.stdout = self.saved

def test():
   print 1
   try:
       for dummy in withmyout_safe3(open("/dev/pts/3", "w")):
           print 2
           raise Exception
   except:
       print 3
   print 4

test()

I get

1
3
4

printed in the current window and "2" printed on /dev/pts/3.

					Andrew




More information about the Python-list mailing list