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.
Python code
23 linesclass 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
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
- Use the built-in open() function as a context manager instead of a custom class.
- 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
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 Context Manager in Python with contextlib.contextmanager 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
Keep learning
Related tutorials and quizzes for this topic.