Junior — Middle
What steps are necessary to implement your own context manager in Python?
sobes.tech AI
Answer from AI
To implement a custom context manager in Python, you need to define an object that implements the following methods:
__enter__(self)— called upon entering the context (with), returns an object that will be bound to the variable afteras.__exit__(self, exc_type, exc_val, exc_tb)— called upon exiting the context, receives information about any exception that occurred, allowing it to handle or suppress it.
Example of a simple context manager:
class MyContextManager:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting context")
if exc_type:
print(f"Handling exception: {exc_val}")
# Return True to suppress the exception
return True
with MyContextManager() as cm:
print("Inside with")
raise ValueError("Error") # Exception will be handled and suppressed
You can also use the contextlib.contextmanager decorator to create a context manager based on a generator, which simplifies the code.