How to create a context manager in Python?
sobes.tech AI
Answer from AI
A context manager can be created in two main ways: using classes and using generators with the @contextmanager decorator.
Creating with a class:
The class must implement the __enter__ and __exit__ methods. The __enter__ method is called when entering the context block (with) and can return an object to be used inside the block. The __exit__ method is called when exiting the block, even if an exception occurs. It takes three arguments: the exception type, exception value, and traceback object. Returning True from __exit__ suppresses the exception.
class FileManager:
def __init__(self, filename, mode):
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 # Do not suppress exceptions
Creating with a generator and @contextmanager:
The contextlib module provides the @contextmanager decorator, which allows creating context managers using generators. Inside the generator function, the yield statement is used. The code before yield runs when entering the context, and the code after yield runs when exiting.
from contextlib import contextmanager
@contextmanager
def open_file(filename, mode):
file = None
try:
file = open(filename, mode)
yield file # Return resource and suspend
finally:
if file:
file.close()
Both methods allow proper resource management, ensuring their release even if errors occur.