Context managers & yield as a doorway
P29.iterators-generators.02 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Iterators & generators
Where next?
This module unlocks
P29.iterators-generators.02 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Iterators & generators
This module unlocks
with blocks and async/await look unrelated — but both stand on the same
mechanism you met in the last module: a frame suspended at yield. This
module closes the pillar by turning a generator into a context manager, then
opening the door that leads to coroutines and P33.
with open(path) as f: calls __enter__ on entry and __exit__ on the way out — always, success or exception. That pairing (acquire/release, begin/commit-or-rollback, lock/unlock) is the whole protocol: two methods and a guarantee.Why it matters — Files, locks, database transactions — anything with a must-run cleanup belongs in a with block, because __exit__ runs even when the body raises.
Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.
Off by default. The mentor always gets your file; this only decides whether your own copy stays here. Copies live in this browser only - they do not follow you to another device, and clearing site data removes them.
Your turn: build a rollback transaction() guard with
@contextmanager, then close the pillar with the interview
question that links yield to coroutines.
Loading exercise…
Loading exercise…
That completes Functions, Decorators & Generators: functions as values,
wrappers as design, iteration as a protocol — and yield left standing as
the doorway P33 walks through.
Loading your notes...