How to Create a Generator Context Manager in Python with contextlib

Create a custom context manager with the @contextlib.contextmanager decorator to manage resources using a generator function.

Medium Python 3.9+ Aug 9, 2026 Comprehensions & generators 13 views 0 copies

Python code

16 lines
Python 3.9+
import contextlib

@contextlib.contextmanager
def temporary_directory():
    """Yield a string and clean up after the block exits."""
    print("Creating temp directory...")
    dir_name = "/tmp/example"
    try:
        yield dir_name
    finally:
        print(f"Removing {dir_name}...")

if __name__ == "__main__":
    with temporary_directory() as tmp:
        print(f"Using: {tmp}")
    print("Done")

Output

stdout
Creating temp directory...
Using: /tmp/example
Removing /tmp/example...
Done

How it works

The @contextlib.contextmanager decorator turns a generator function into a context manager. The yield statement splits the code into two parts: everything before it runs on entry, and everything after runs on exit. Using try/finally around yield ensures cleanup code always executes, even if an exception occurs inside the with block. The yielded value becomes the as target available inside the with block.

Common mistakes

  • Forgetting the `try/finally` block around `yield` so cleanup runs on exceptions
  • Using `return` instead of `yield` inside the generator function
  • Not catching exceptions to suppress or transform them after the yield

Variations

  1. Use `@contextlib.asynccontextmanager` for async with-blocks
  2. Create a class-based context manager with `__enter__` and `__exit__` methods

Real-world use cases

  • Automatically closing database connections or file handles after a block completes.
  • Setting up and tearing down temporary test environments or fixtures in unit tests.
  • Acquiring and releasing thread locks or other synchronization primitives safely.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.