Lesson · Resource Management
Context Managers
55 min readContext Managers
Context managers turn resource lifetime into structured control flow. Files, locks, transactions, and temporary state all benefit from cleanup that is tied to lexical scope.
Learning goals
- Explain how
withmaps the acquire, use, and release phases to__enter__and__exit__. - Use a file through
Path.open(..., encoding="utf-8")and say exactly when it gets closed. - Predict what happens when an exception fires inside a
withblock, both to the resource and to the exception. - Rewrite a manual
close()orrelease()sequence as a block and name the failure modes the block removes.
Mental model
The flow carries two guarantees worth naming: the body runs only after acquisition succeeds, and the release step runs on every exit from the body, including exceptions, return, and break. The mechanism is the context manager protocol: __enter__ supplies the object bound by as, and __exit__ performs the cleanup and reports whether an exception should keep propagating. Files and locks are just the common resources that need exactly this shape.
Mental model
read it top to bottom
acquire resource → enter scope → use resource → guaranteed cleanup
Core idea
A context manager is a resource lifetime expressed as control flow: acquisition happens in __enter__, release in __exit__, and the with statement guarantees the second runs once the first did. That guarantee is the point, because it holds across exceptions, early returns, and loops, which manual close() calls do not. The idiom matters most for resources whose release must happen even when the block fails.
with
with guarantees that a context manager's exit logic runs when the block leaves. This converts cleanup from a convention into a control-flow guarantee.
Files
A file opened in a with statement is the canonical context manager: __enter__ returns the file object bound by as, and __exit__ closes it even when an exception interrupts the body. Raising inside the block still closes the file, and the exception continues after the cleanup runs. Path.open and the built-in open both support this form; pass encoding="utf-8" explicitly so the text format does not depend on the machine's default.
Locks
A lock is a mutual-exclusion primitive, and its context manager form acquires the lock on entry and releases it on exit, even when the protected code raises. Using threading.Lock with with removes the classic bug where an early return or exception skips the manual release() and stalls every other thread waiting on the lock. The release belongs to the same scope as the critical section it protects.
Resource lifecycle
A resource lifecycle has acquisition, use, and release phases. Context management binds release to scope so every exit path follows the cleanup rule.
Exception-safe cleanup
Exception-safe cleanup runs even when the body fails. with and finally are the primary language tools for guaranteeing this behavior.
Walkthrough
Path("example.txt")builds a path object without touching the disk; the file comes into existence when the first block opens it with mode"w".- In the write block,
path.open("w", encoding="utf-8")is the acquisition,as filebinds the object that__enter__returned, andfile.write("hello\n")runs inside the protected region; when the block ends, the manager closes the file before the next statement executes. - The read block opens the same path in
"r"mode andfile.read()returns the text written earlier, which shows the write was flushed and closed in order. Both blocks stateencoding="utf-8"explicitly, so the file format does not depend on the machine default. - Predict before running: what the script prints, and what changes if the read block moves above the write block on a fresh directory.
Experiments to try
- Run the example and check
example.txton disk; printfile.closedinside the write block and again right after it, while the name is still in scope. - Force an exception inside the write block, for example
1 / 0afterfile.write("partial"), catch it outside, then read the file. The partial text is flushed on close, and the exception still propagated. - Move the read block above the write block on a fresh directory, and record the exception type and the line that raised it.
- Rewrite the write block as
try/finallywith theopencall inside thetryand point the path at a missing folder. Explain which exception reaches the caller and why the original one is hidden.
Common mistakes
- Using the resource after the block ends: the file or lock was already closed or released, so the next operation fails, typically with
ValueError: I/O operation on closed file. - Expecting
withto suppress exceptions: cleanup runs, and then the exception keeps propagating, because__exit__returns a falsy value by default; stopping it takes a manager built for that, such ascontextlib.suppress. - Acquiring inside
tryand releasing infinallyby hand: when the acquisition itself fails,finallystill runs and raises a second error against a name that was never bound, masking the original failure. - Closing the resource inside the block as well: the extra
close()either does nothing and blurs who owns the release, or errors; the block should be the single owner.
Practice: Easy
- Run the worked example, then print
file.closedinside the first block and after it. Record both values and the file's content on disk. - Move the read block above the write block on a fresh directory and record the exception type, message, and line.
- Change
"w"to"r"in the first block on a fresh directory, note the exception, then restore the mode.
Practice: Medium
- Rewrite the write block with plain
openand a manualtry/finallythat closes infinally. List what thewithversion did for you and what the manual version leaves to discipline. - Protect a counter incremented by two threads with
with lock:for a few thousand iterations each, then remove the lock and explain the difference you observe, including why a small run may not show one. - Take a
close()orrelease()call in your own code and move it into awithblock. Name the exit paths (exception,return,break) the old version failed to cover.
Practice: Hard
- Design an
Openedcontext manager class whose__enter__opens the file withPath.openand whose__exit__closes it. Document what__enter__returns and what__exit__should do when the body raises. - Build a failure lab around the write block: raise inside the block after a partial write, then examine the file and the traceback. Run the same scenario with a manual open and no
finally, and compare what the file and the traceback look like. - Connect this lesson to
contextlib(lesson 78): list the two protocol methods a class needs, then predict what a generator-based manager will change about how the cleanup is written.
Lesson checklist
- I can draw the acquire, use, release flow and say which protocol method handles each end.
- I can explain why the
withblock's cleanup runs even when the body raises. - I can rewrite a manual
close()orrelease()pattern as awithblock and name what improves. - I can read
file.closedto confirm when the cleanup ran.
Remember
Context managers turn a resource lifetime into control flow: `__enter__` acquires, the block uses, and `__exit__` releases on every exit path, including exceptions. That guarantee is why files and locks are used through `with` instead of manual `close()` and `release()` calls, which any early exit can skip. The pattern generalizes: any pairing of acquire and release that must stay together belongs in a context manager.
Interview angles
What is the main purpose of **with**?+
with guarantees that a context manager's exit logic runs when the block leaves. This converts cleanup from a convention into a control-flow guarantee.
What should you pay attention to when using **Files**?+
A file opened in a with statement is the canonical context manager: __enter__ returns the file object bound by as, and __exit__ closes it even when an exception interrupts the body. The exception still continues after the cleanup runs.
How does **Locks** fit into this lesson?+
A lock used with with is acquired on entry and released on exit, even when the protected code raises. That removes the bug where an early return or exception skips a manual release() and stalls every other thread waiting on the lock.
Why is `with` more reliable than calling `close()` at the end of a function?+
The __exit__ step runs on every path out of the block, including exceptions and early returns, while a trailing close() line is simply skipped when the function exits earlier. That is why the block, not the last line, should own the release.