Junior — Middle
What is the protocol implemented by the context manager in Python?
sobes.tech AI
Answer from AI
In Python, a protocol implemented by a context manager is a set of methods that allow an object to be used in a with statement. Such an object must implement the __enter__() and __exit__() methods.
__enter__()is called when entering thewithblock. It typically prepares the resource and can return an object that will be accessible inside the block.__exit__(exc_type, exc_val, exc_tb)is called when exiting thewithblock, even if an exception occurs inside the block. It is responsible for releasing resources and handling exceptions.
Example:
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
# Return False to not suppress exceptions
return False
with FileManager('test.txt', 'w') as f:
f.write('Example of using a context manager')
Thus, the context manager protocol provides convenient and safe resource management.