Build a Context Manager in Python with contextlib.contextmanager
Create a reusable context manager that safely opens and closes files using the contextlib contextmanager decorator.
Python code
18 linesfrom contextlib import contextmanager
@contextmanager
def managed_file(filename, mode='r'):
"""Context manager that opens and closes a file safely."""
file = open(filename, mode)
yield file
file.close()
if __name__ == "__main__":
# Write a sample file
with managed_file("sample.txt", "w") as f:
f.write("Hello, context managers!")
# Read the file back using the context manager
with managed_file("sample.txt") as f:
content = f.read()
print(content)
Output
Hello, context managers!
How it works
The @contextmanager decorator lets you write a context manager as a generator function. The yield statement splits the function into two parts: code before it runs on __enter__, and code after it runs on __exit__. Here, the file is opened before the yield and closed after the block finishes. This ensures the resource is always released, even if an exception occurs. Using the decorator avoids writing a class with __enter__ and __exit__ methods for simple use cases.
Common mistakes
- Forgetting to wrap the yield in a try/finally block if you want to handle exceptions or ensure cleanup on errors.
- Using this pattern when you need a manager that supports re-entry or multiple times.
- Not specifying the correct file mode, which can cause errors like reading a file opened without 'r'.
Variations
- Write the same manager as a class with `__enter__` and `__exit__` methods for more control.
- Use `open()` directly with the `with` statement for simpler file handling without a custom manager.
Real-world use cases
- Managing database connections so they always close after a transaction block.
- Temporarily changing working directory and restoring it afterwards.
- Timing code execution blocks while ensuring the timer stops correctly.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
- Call a Function Dynamically by Name in Python easy
Keep learning
Related tutorials and quizzes for this topic.