Created
July 30, 2014 16:47
-
-
Save mitsuhiko/aabc29659d06b429fe58 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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