@contextlib.contextmanager
def _nested(*managers):
 exits = []
 vars = []
 exc = (None, None, None)
 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)):
   raise_exc_info(exc)

@ contextlib . contextmanager def _nested ( * managers ) : exits = [ ] vars = [ ] exc = ( None , None , None ) 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 ) ) : raise_exc_info ( exc )
support multiple context managers in a single with-statement .