@contextmanager
def nested(*managers):
 exits = []
 vars = []
 exc = (None, None, None)
 try:
  try:
   for mgr in managers:
    exit = mgr.__exit__
    enter = mgr.__enter__
    vars.append(enter())
    exits.append(exit)
   (yield vars)
  except:
   exc = sys.exc_info()
  finally:
   while exits:
    exit = exits.pop()
    try:
     if exit(*exc):
      exc = (None, None, None)
    except:
     exc = sys.exc_info()
   if (exc != (None, None, None)):
    reraise(exc[0], exc[1], exc[2])
 finally:
  del exc

@ contextmanager def nested ( * managers ) : exits = [ ] vars = [ ] exc = ( None , None , None ) try : try : for mgr in managers : exit = mgr . __exit__ enter = mgr . __enter__ vars . append ( enter ( ) ) exits . append ( exit ) ( yield vars ) except : exc = sys . exc_info ( ) finally : while exits : exit = exits . pop ( ) try : if exit ( * exc ) : exc = ( None , None , None ) except : exc = sys . exc_info ( ) if ( exc != ( None , None , None ) ) : reraise ( exc [ 0 ] , exc [ 1 ] , exc [ 2 ] ) finally : del exc
implement contextlib .