Lesson · Resource Management
contextlib
55 min readcontextlib
`contextlib` supplies utilities for writing and composing context managers without unnecessary classes. `ExitStack` is especially valuable when the number of resources is dynamic.
Learning goals
- Write a context manager as a generator function and say which code is acquisition, which value
yieldbinds, and where the release lives. - Choose among
closing,suppress, andnullcontextfor a given resource or expected failure. - Compose several managers with
ExitStackand predict the order in which their cleanups run. - Explain when a generator-based manager cannot be reused and a fresh one is required per
with.
Mental model
The tools cover different shapes of the same job: @contextmanager turns a generator function into a manager, closing wraps any object with a close() method, suppress turns listed exceptions into silence, nullcontext is the do-nothing manager, and ExitStack composes an arbitrary number of the others at runtime. The worked example combines the first and the last: a generator-based manager entered twice inside one stack.
Mental model
read it top to bottom
write a manager from a generator function → @contextmanager manage one object with a close() method → closing ignore listed expected exceptions → suppress do nothing, bind a value → nullcontext compose any number of managers or callbacks → ExitStack
Core idea
contextlib exists so resource handling does not require a class per resource: a generator function with @contextmanager expresses acquisition before the single yield and release after it, and ExitStack composes any number of managers, including ones discovered at runtime. The module also supplies the small adapters (closing, suppress, nullcontext) that cover the common shapes instead of forcing a custom class each time. The design question is whether the manager is written once (generator) or composed dynamically (stack).
@contextmanager
@contextmanager turns a generator function into a context manager: the code before yield is the acquisition, the yielded value is what as binds, and the code after yield, normally inside a finally, is the release. An exception in the block is thrown into the generator at the yield, so a try/finally there is what guarantees cleanup. The generator runs once per with statement, so a manager instance cannot be reused after its block ends.
closing
closing(obj) creates a context manager that calls obj.close() when the block exits, which adapts objects that have a close method but do not implement the context manager protocol themselves. The wrapped object comes back out of __enter__, so as still binds the original, not a wrapper.
suppress
suppress(*types) creates a manager that swallows exceptions of the listed types and lets everything else propagate past the block. It replaces the empty try/except SomeError: pass pattern with a form that states the intent in the with line: with suppress(FileNotFoundError): path.unlink(). Suppressing a wide type makes failures disappear silently, so list only the expected types.
nullcontext
nullcontext(value) is a context manager that does nothing: it yields value on entry and performs no cleanup on exit. It exists so code that only sometimes needs a manager can use one with statement for both cases, for example when a function receives an optional resource and falls back to a plain object. With no argument, as binds None.
ExitStack
ExitStack dynamically composes an arbitrary number of context managers and cleanup callbacks. It is useful when resources are discovered in loops or conditional branches.
Walkthrough
named_bufferis a generator function:buffer = StringIO()runs at acquisition,yield buffersupplies the value thatasbinds, and thefinallyafter the yield prints the release message even if the body raises.with ExitStack() as stack:creates an empty stack. Eachstack.enter_context(named_buffer("a"))enters a manager immediately and registers its exit for later, returning the yielded value, soaandbare the buffers themselves.a.write("hello")andb.write("world")run while both managers are open. When the block ends,ExitStackunwinds in reverse:b's release prints first, thena's, so the output isb closedfollowed bya closed.- Predict before running: the exact two lines printed at exit, and in which order.
Experiments to try
- Run the example and record the order of the two printed lines; swap the two
enter_contextcalls and confirm the order flips. - Raise inside the
withblock after both writes and confirm bothclosedlines still print before the traceback. - Register
stack.callback(print, "manual cleanup")after entering both buffers and predict where its line falls in the output before running. - Replace the
ExitStackwith two nestedwithstatements and compare what fixed nesting gives up relative to entering managers in a loop.
Common mistakes
- Skipping
try/finallyaround theyield: the body's exception is thrown into the generator at theyield, and withoutfinallythe release code after it never runs. - Reusing a
@contextmanagerinstance for a secondwithblock: the generator finished after the first use, so the second__enter__raises aRuntimeError. Create a fresh manager for each use. - Suppressing broadly:
suppress(Exception)makes every failure of that type vanish with no log, hiding bugs along with the expected condition. List the narrow types you actually expect. - Expecting cleanup in entry order:
ExitStackunwinds last entered first, and callbacks registered withcallback()follow the same rule, so enter resources in dependency order to get a safe reverse cleanup.
Practice: Easy
- Run the worked example and record the order of the two
closedlines; explain it with the stack's reverse unwinding. - Add a third buffer to the stack and predict the full exit order before running.
- Write a
@contextmanagerfunction that printsenterandexitaroundyield, use it in onewithstatement, and confirm the printed order.
Practice: Medium
- Delete the
try/finallyfromnamed_buffer, raise inside thewithblock, and record what prints; restore it and repeat. - Replace the
ExitStackusage with two nestedwithstatements, then demonstrate the case the stack handles and nesting cannot: entering buffers from aforloop whose count is only known at runtime. - Use
suppressto ignore one expected failure, such as deleting a missing file, andnullcontextto route an optional resource through a singlewithstatement.
Practice: Hard
- Design a
temporary_settings(mapping)generator-based manager that applies entries on entry and restores the previous values on exit, including when the body raises. Document whatyieldreturns and where thetry/finallygoes. - Build a failure lab around
ExitStack: register a cleanup that raises, then another that succeeds, and read which exception wins and what still ran. Explain the result with reverse unwinding and exception replacement. - Connect this lesson to lesson 77: write the same manager as a class and as a generator function, list what the generator version removes, and name one case where the class is still the better choice.
Lesson checklist
- I can write a generator-based manager and say where the acquisition, the
yield, and the release live. - I can choose among
closing,suppress, andnullcontextfor a given shape of resource or expected failure. - I can explain the order in which
ExitStackruns its cleanups and why it is reversed. - I can contrast the class-based manager from lesson 77 with the generator-based one and pick one deliberately.
Remember
`contextlib` covers resource management without a class per resource: `@contextmanager` turns a generator function into a manager with acquisition before `yield` and release in the `finally` after it, while `ExitStack` composes any number of managers, including ones created in loops. The adapters cover the common shapes: `closing` for objects with `close()`, `suppress` for listed expected exceptions, and `nullcontext` when no cleanup is needed.
Interview angles
What is the main purpose of **@contextmanager**?+
It turns a generator function into a context manager: code before yield is the acquisition, the yielded value is what as binds, and the code after yield is the release. An exception in the block is thrown into the generator, so that release code needs a try/finally.
What should you pay attention to when using **closing**?+
closing(obj) calls obj.close() when the block exits, adapting objects that have a close method but do not implement the context manager protocol. The wrapped object comes back from __enter__, so as binds the original.
How does **suppress** fit into this lesson?+
suppress(*types) swallows exceptions of the listed types and lets everything else propagate, replacing the empty try/except pass pattern with intent stated in the with line. Suppressing a wide type hides bugs silently, so list only the expected exceptions.
Why does a `@contextmanager`-based manager fail on a second `with` statement, and what should you do instead?+
The generator behind it runs only once: after the first block the generator has finished, so entering again raises a RuntimeError. Create a fresh manager for each use instead.