Junior — Middle
What special methods need to be implemented when creating a custom context manager in Python?
sobes.tech AI
Answer from AI
To create a custom context manager in Python, you need to implement two special methods:
-
__enter__(self): called when entering thewithblock. Usually, resource preparation occurs here. The method should return an object that will be bound to the variable afteras. -
__exit__(self, exc_type, exc_val, exc_tb): called when exiting thewithblock, even if an exception occurs inside the block. Resource cleanup usually happens here. The parameters allow handling exceptions if they occur.
Example:
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"Handled exception: {exc_type}")
with MyContextManager() as cm:
print("Inside with block")