Context managers & yield as a doorway

P29.iterators-generators.02 · Audience: guest, it-ml, language-pro · Prerequisites: Iterators & generators

Real LLM grading for this pageLLM grading (this page):

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.

Step 1 / 4with: enter, exit, guaranteed
ⓘ Concept: The context-manager protocol
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 the mentor about this module

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.

Ctrl/Cmd + Enter to send

🎓 Practice ladder

2 graded rungs · ~18 min

Your turn: build a rollback transaction() guard with @contextmanager, then close the pillar with the interview question that links yield to coroutines.

Rung 1 — a transaction guard with @contextmanager

Loading exercise…

Interview rung — yield as a doorway to coroutines (free-form)

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.

Where next?