Middle
What tools can be used to create your own context manager in Python?
sobes.tech AI
Answer from AI
A context manager can be created in two main ways:
- Using classes with
__enter__and__exit__methods. - Using the
contextmanagerdecorator from thecontextlibmodule.
Example with a class:
class MyContextManager:
def __enter__(self):
# Actions upon entering the context
print("Entering context")
return self # Can return an object for use inside with
def __exit__(self, exc_type, exc_val, exc_tb):
# Actions upon exiting the context
# exc_type, exc_val, exc_tb contain information about an exception if it occurred
print("Exiting context")
# Returning True suppresses the exception, False (or nothing) - does not
return False
# Usage
with MyContextManager() as cm:
print("Inside context")
Example with the contextmanager decorator:
from contextlib import contextmanager
@contextmanager
def my_context_manager_func():
# Actions upon entering the context (before yield)
print("Entering context")
yield # Returns an object for use inside with
# Actions upon exiting the context (after yield)
print("Exiting context")
# Usage
with my_context_manager_func() as cm:
print("Inside context")
The choice between these methods depends on the complexity of the logic and preferences. The class approach is more explicit and suitable for complex resource management logic. The contextmanager decorator is convenient for simpler cases and when the logic can be expressed as a generator.