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.
Python code
16 linesimport 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
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
- Use `@contextlib.asynccontextmanager` for async with-blocks
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.