Build Generator Context Managers
Core idea
contextlib.contextmanager turns a generator function into a context-manager factory. The generator runs to its single yield for entry; the yielded value is bound by as. At exit it resumes, with any body exception raised at the yield point. Use finally for cleanup.
from contextlib import contextmanager@contextmanagerdef marker(): print("start") try: yield "ready" finally: print("end")with marker() as label: print(label)The @ syntax applies contextmanager to the function, equivalent to marker = contextmanager(marker). finally runs when the block ends.
Clean up on a failure
from contextlib import contextmanager@contextmanagerdef session(): try: yield finally: print("cleanup")try: with session(): raise ValueError("bad")except ValueError: print("handled")Cleanup runs before the outer handler, while the exception remains visible.
Common mistake
A contextmanager generator must yield exactly once. If it catches a body exception merely to log it, re-raise it to avoid accidental suppression. Create a fresh manager for each use.
Practice
Write a manager yielding a mutable list, then clear the list in finally. Test normal and exceptional exits.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generator context manager contract
Check your understanding of generator context managers.
What is printed?
from contextlib import contextmanager@contextmanagerdef cm(): yield 5with cm() as n: print(n)Which exception occurs?
from contextlib import contextmanager@contextmanagerdef cm(): yield 1 yield 2with cm(): passWhere should cleanup generally go?
What if a manager catches an error only to log it?