Applying variable context managers
When using context managers, you must rely on the with statement to apply them. While it's possible to apply more than one context manager per statement by separating them with commas, it's not as easy to apply a variable number of them:
@contextlib.contextmanager
def first():
print('First')
yield
@contextlib.contextmanager
def second():
print('Second')
yieldThe context managers that we want to apply must be known when writing the code:
>>> with first(), second():
>>> print('Inside')
First
Second
InsideBut what if sometimes we only want to apply the first context manager, and sometimes we want to apply both?
How to do it...
contextlib.ExitStack serves various purposes, one of which is to allow us to apply a variable number of context managers to a block.
For example, we might want to apply both context managers only when we are printing an even number in a loop:
from contextlib import ExitStack
for n in range(5):
with...