Junior — Middle
What steps and elements are needed to create a context manager in a Python class?
sobes.tech AI
Answer from AI
To create a context manager in a Python class, you need to implement two special methods:
-
__enter__(self)— called when entering thewithblock. Usually, resources are initialized here, and the object that will be accessible inside the block is returned. -
__exit__(self, exc_type, exc_val, exc_tb)— called when exiting thewithblock, regardless of whether an exception occurred or not. Resources are usually released here.
Example:
class MyContextManager:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting context")
# Exceptions can be handled here if needed
with MyContextManager() as manager:
print("Inside with block")
Thus, the key steps are to define these two methods in the class so that the object can be used in a with statement.