How does `@contextlib.contextmanager` let you write a context manager as a generator function instead of a class?
Answer
`@contextlib.contextmanager` wraps a generator function that yields exactly once: everything before the `yield` becomes the `__enter__` logic, and the yielded value becomes the `as` binding. If the `with` body raises, that exception is thrown back into the generator at the point of the `yield` expression — so code written after `yield` only runs as guaranteed cleanup if it is wrapped in its own `try`/`finally` around the `yield`, exactly like a hand-written `__enter__`/`__exit__` pair would need. The canonical pattern is `resource = acquire(); try: yield resource; finally: release(resource)`; skipping the `try`/`finally` means an exception from the `with` body can skip the cleanup code entirely, which is the most common mistake with this decorator. Done correctly, it still avoids writing a full class with separate `__enter__`/`__exit__` methods for simple setup/teardown pairs.
Strong answer includes
- code before yield is __enter__, yielded value is the as binding
- cleanup after yield only runs reliably if wrapped in your own try/finally around the yield
- an exception from the with body is thrown back in at the yield point
Practical example
@contextmanager
def managed_file(path):
f = open(path)
try:
yield f
finally:
f.close()guarantees
f.close()runs even if code inside the
withblock raises, because the
yieldis wrapped in
try/
finally.