A context manager controls setup and cleanup around a block of code, usually used through a with statement.
Implement success and failure exits, handle acquired resources and make exception suppression a deliberate choice.
A report write can fail after the destination has already been emptied. Cleanup alone cannot bring the old report back. We will separate acquisition, work, successful replacement and failure cleanup, then use a context manager to make those paths explicit.

Announce a stage, pass or fail
A pipeline stage should report whether it succeeded, without every stage
writing that logic by hand. A class with __enter__ and __exit__ does it
once:
The parse stage reported its failure and still let the exception
through, because __exit__ returned None. That's the right default — a
manager cleans up and reports; it doesn't decide the error doesn't matter.
Returning something truthy is an opt-in to silence, and it's easy to get
wrong by accident:
class Hush:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
return True
with Hush():
1 / 0
print("inside")
print("after")Preparing this topic’s interactive investigation…
Open every file in a batch at once
Quarry sometimes needs to open every file in a batch together — and the
batch size comes from the data, so with a, b, c: won't do.
contextlib.ExitStack holds a variable number of managers and unwinds them
all when its own with ends:
enter_context enters a manager now and schedules its exit for later. If
opening the third file had failed partway through, the first two would
still be closed — nothing leaks. When several managers are known ahead of
time, plain nesting unwinds the same way, last-in first-out:
log = []
class Tag:
def __init__(self, name):
self.name = name
def __enter__(self):
log.append("enter " + self.name)
def __exit__(self, exc_type, exc, tb):
log.append("exit " + self.name)
with Tag("a"), Tag("b"):
log.append("body")
print(", ".join(log))Here is the same unwinding as a diagram — push on the way in, pop on the way out, and an exception takes the same exit route:
Rewrite a report without losing the old one on a crash
Last week Quarry's machine lost power while rewriting its summary report.
The file was opened with "w" — which empties it immediately — and only
half the new report reached disk. The fix: never write over the real file.
Write into a temporary sibling, and only when it's complete, rename it
over the original with os.replace, which, when successful on the same filesystem, atomically changes the
destination name. Readers opening that name see the old file or the completed
new file. Power-loss durability needs additional care, discussed below.
Writing a class with two dunder methods for a five-line cleanup is a lot of
ceremony. @contextmanager turns a generator into the same thing. A
generator is a function that can pause — calling it doesn't run it; each
resume runs up to the next yield and parks there with its locals intact:
That try/finally isn't decoration. If the with body raises,
@contextmanager throws that exception into the generator, at the
yield line. Without a finally, the lines after yield never run, and
the cleanup silently goes missing:
from contextlib import contextmanager
log = []
@contextmanager
def opened(name):
log.append("open " + name)
yield name
log.append("close " + name)
try:
with opened("a.log"):
log.append("body")
raise ValueError("bad row")
except ValueError:
pass
print(log)Quarry's guard follows the same shape: before the yield, open the .tmp
sibling; yield the open file for the caller to write into; if the body
finished, close it and os.replace it over the original; if it raised,
close it, delete the .tmp, and re-raise — the guard cleans up, it
doesn't pretend the write succeeded.
Draw the success and failure exits separately
yield in a generator context manager marks a handoff to the caller's block. It is not the commit point. The commit belongs after the block finishes successfully; cleanup belongs on every Python exit path, using the exception and cleanup rules established earlier.
| Event | Old report | Temporary report | Exception |
|---|---|---|---|
| temporary file opened | unchanged | being written | none |
| caller raises halfway | unchanged | close and remove | propagate original error |
| caller finishes | unchanged until replacement | close, then replace destination | propagate replacement errors |
Closing a file flushes Python's buffered writes. A successful same-filesystem os.replace gives an atomic name replacement; it does not, by itself, promise survival after sudden power loss. Durable local storage may require flushing and syncing the file and directory under the operating system's rules. That is a different requirement from keeping readers from observing a partially rewritten file.
Two further boundaries matter. If __enter__ fails, Python does not call that manager's __exit__; acquisition code must clean up any resources it already acquired. And neither finally nor a context manager can run after every possible event: a forcibly killed process or power failure stops Python itself.
Design a failure probe: use the exercise's intentional exception after writing half the new report. Check all three observations: old content survives, no temporary file remains, and the caller still sees failure. Then consider two writers choosing the same .tmp filename. A production writer needs a uniquely created temporary sibling; the exercise's fixed sibling assumes one writer. Do not widen its tests into a concurrency or durability guarantee.
References: context-manager cleanup and replacement semantics.
Quick practice
Run it. Only [4] prints, not [4, 10]. Move the with so each value gets its own chance.
from contextlib import closing
class Handle:
def __init__(self):
self.closed = False
def close(self):
self.closed = True
h = Handle()
with closing(h) as handle:
pass
print(handle is h, h.closed)class Counter:
def __enter__(self):
return 0
def __exit__(self, exc_type, exc, tb):
return False
with Counter() as n:
n += 1
print(n)from contextlib import contextmanager
@contextmanager
def guarded():
try:
yield "ok"
except ZeroDivisionError:
yield "recovered"
with guarded() as v:
1 / 0
print(v)🎯 Your turn
Write replacing(path):
atomic_write("old", "new", False)→{"content": "new", "files": ["report.txt"]}atomic_write("old report", "new report", True)→{"content": "old report", "files": ["report.txt"]}
Hint — tmp = path.with_name(path.name + ".tmp"); wrap yield f in
try/except BaseException/else; success replaces, failure unlinks and re-raises.
Then press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write a class Guard whose __enter__ appends "enter" to a list and whose __exit__ appends "exit" (and returns nothing). Then write guarded_events(fail): inside with Guard(events): append "body" and, if fail, raise ValueError. Catch it outside the with and append "caught". Return the list.
Write parse_ints(values) that converts each string to an int and skips the ones that fail, using contextlib.suppress(ValueError) rather than try/except. parse_ints(["4", "x", "10"]) → [4, 10].
Write a class Tag(name, log) that logs "enter NAME" and "exit NAME". Then write nest_order(names) that enters one Tag per name using contextlib.ExitStack (you don't know how many there are), appends "body" once inside, and returns the log.
Quarry runs stages and wants a report line per stage without one failure stopping the rest. Write @contextmanager stage(name, report) that appends "NAME: ok" if the body finishes, or "NAME: ExcType" and SWALLOWS the exception if it raises. Then run_stages(divisors) runs 100 / d inside stage(f"s{i}", report) for each divisor and returns the report.
Write a class-based manager Transaction(store): on enter it snapshots the dict (dict(store)), on a clean exit it keeps the changes, and on an exception it restores the snapshot and swallows the error (only ValueError). Then apply_batches(store, batches): each batch is a list of [key, delta] pairs; apply each batch inside a Transaction, adding delta to store.get(key, 0) and raising ValueError if any value would go below zero. Return {"store": store, "applied": [True/False per batch]}.
A teammate writes an @contextmanager with setup, then yield, then cleanup — no try. It works in every test they ran. Explain exactly when the cleanup is skipped, why, and what __exit__ returning True has to do with it.