Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Errors & context managersMiddleCommonPractical

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

Python example
@contextmanager
def managed_file(path):
    f = open(path)
    try:
        yield f
    finally:
        f.close()

guarantees

Python example
f.close()

runs even if code inside the

Python example
with

block raises, because the

Python example
yield

is wrapped in

Python example
try

/

Python example
finally

.

#context-managers#contextlib

Sources

contextlib — Utilities for with-statement contextsPython Software Foundation · Context manager helpers, including contextmanager and ExitStack