Interview frequency: …
Short answer
It provides tools to build and combine context managers: contextmanager to write a manager as a generator, ExitStack to manage a variable number of resources, suppress to ignore a specific exception, plus closing and nullcontext.
Explanation
A context manager reduces repeated try/finally and guarantees the resource lifecycle. ExitStack is useful when you do not know the number of files or connections in advance; it guarantees that everything opened gets closed even if opening one of them fails. suppress makes ignoring an expected error explicit and narrow. For asynchronous code there are asynccontextmanager and AsyncExitStack.
Code example
from contextlib import ExitStack, suppress
import os
def merge(paths: list[str], out: str) -> None:
with ExitStack() as stack:
files = [stack.enter_context(open(p)) for p in paths]
with open(out, "w") as target:
for f in files:
target.write(f.read())
with suppress(FileNotFoundError):
os.remove("tmp.lock")Common mistakes
- Opening several files in a loop without guaranteeing that those already opened get closed when one fails.
- Using suppress(Exception), so every error disappears instead of only the expected one.