Skip to content

Instantly share code, notes, and snippets.

@mitsuhiko
Created July 30, 2014 16:47
Show Gist options
  • Save mitsuhiko/aabc29659d06b429fe58 to your computer and use it in GitHub Desktop.
Save mitsuhiko/aabc29659d06b429fe58 to your computer and use it in GitHub Desktop.
import sys
from contextlib import nested
@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[0], exc[1], exc[2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment