How to Write a Context Manager Class in Python

Define a class with __enter__ and __exit__ to manage file resources safely using the with statement.

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

Python code

23 lines
Python 3.9+
class FileReader:
    def __init__(self, filename, mode="r"):
        self.filename = filename
        self.mode = mode
        self.file = None

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()
        return False


if __name__ == "__main__":
    with FileReader("example.txt", "w") as f:
        f.write("Hello, context manager!")

    with FileReader("example.txt") as f:
        content = f.read()
        print(content)

Output

stdout
Hello, context manager!

How it works

The __enter__ method opens the file and returns the file object, which is bound to the as variable in the with statement. The __exit__ method is called automatically when the block exits, closing the file to prevent resource leaks. Returning False from __exit__ propagates any exceptions raised inside the block, allowing normal exception handling. This pattern encapsulates resource cleanup and makes code more readable.

Common mistakes

  • Forgetting to return the file object from __enter__.
  • Returning True from __exit__ to suppress exceptions unintentionally.
  • Not handling the case where __enter__ might fail midway.

Variations

  1. Use the built-in open() function as a context manager instead of a custom class.
  2. Use contextlib.contextmanager decorator to create a generator-based context manager.

Real-world use cases

  • Automatically releasing database connections or network sockets after a block of operations.
  • Managing file handles in data processing scripts to avoid corruption from unclosed files.
  • Implementing custom lock acquisition and release in multi-threaded applications.

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.