August 2018
Intermediate to advanced
366 pages
10h 14m
English
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 ExitStack() as stack:
stack.enter_context(first())
if n % 2 == 0:
stack.enter_context(second())
print('NUMBER: {}'.format(n))
The result will be that the second is only added to the context, and thus invoked for even numbers:
First Second NUMBER: 0 First NUMBER: 1 First Second NUMBER: 2 First NUMBER: 3 First Second NUMBER: 4
As you can see, for 1 and 3, only First is printed.
Of course, when exiting the context declared through ...