Sub topic 3
Several Context Managers and Contextlib
Assume you know Python functions, classes, exceptions, generators, decorators, and basic file operations. A context manager controls setup and cleanup around a with block.
Several managers in one `with` statement
Separate managers with commas. Python enters them from left to right and exits them in reverse order.
with open("input.txt") as source, open("output.txt", "w") as target:
target.write(source.read())This behaves like nested blocks. If opening the second file fails, Python still closes the first file.
flowchart TD
A[Enter first manager] --> B[Enter second manager]
B --> C[Run the body]
C --> D[Exit second manager]
D --> E[Exit first manager]caption: Context managers exit in reverse order alt: A flowchart showing left-to-right entry and reverse-order cleanup
Useful tools in `contextlib`
The standard contextlib module provides ready-made managers:
suppress(ErrorType)ignores selected exceptions.closing(obj)callsobj.close()during cleanup.redirect_stdout(stream)temporarily sendsprint()output to a stream.nullcontext(value)supplies an optional manager without special-case code.
Use suppress narrowly. Hiding an unexpected exception can make a program appear successful when it failed.
`ExitStack` for a variable number of managers
A regular with statement works well when the number of resources is known. ExitStack collects managers dynamically and still cleans them up in reverse order.
from contextlib import ExitStack
paths = ["one.txt", "two.txt"]
with ExitStack() as stack:
files = [stack.enter_context(open(path)) for path in paths]
text = "".join(file.read() for file in files)
print(text)If a later open() fails, already-open files are closed.
Reuse and reentrancy
Some managers are single-use. A generator-based manager created by @contextmanager usually cannot be entered twice. A reusable manager can support separate with statements. A reentrant manager can safely be entered while it is already active.
Do not assume reuse is safe. Read the manager's documentation or write a test for repeated and nested use.
`async with`
Asynchronous managers use __aenter__ and __aexit__. The async with statement awaits both operations.
import asyncio
from contextlib import asynccontextmanager
@asynccontextmanager
async def connection():
print("open")
try:
yield
finally:
print("close")
async def main():
async with connection():
await asyncio.sleep(0)
asyncio.run(main())Pitfalls and testing
Test normal completion, exceptions in the body, failed setup, repeated entry, and nested entry. Confirm that cleanup runs and that exceptions propagate unless suppression is intentional. Keep __exit__ returning False when the manager should not hide errors.
Exercise
In what order do three context managers enter and exit?
Show answer
They enter from left to right and exit from right to left.