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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

18 lines
Python 3.9+
from 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

stdout
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

  1. Write the same manager as a class with `__enter__` and `__exit__` methods for more control.
  2. 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

Run this sample

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

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.