We have code that invokes a variable number of context managers depending on runtime parameters:
from contextlib import nested, contextmanager
@contextmanag
It's a little vexing that the python3 maintainers chose to break backwards compatibility, since implementing nested
in terms of ExitStack
is pretty straightforward:
try:
from contextlib import nested # Python 2
except ImportError:
from contextlib import ExitStack, contextmanager
@contextmanager
def nested(*contexts):
"""
Reimplementation of nested in python 3.
"""
with ExitStack() as stack:
for ctx in contexts:
stack.enter_context(ctx)
yield contexts