Junior — Middle
What protocol does the resource management mechanism in the context managers operate on?
sobes.tech AI
Answer from AI
The resource management mechanism in Python's context managers operates through a protocol that requires the implementation of two special methods: __enter__ and __exit__. This protocol allows for automatic allocation and release of resources, such as opening and closing files, or setting and releasing locks.
Example of a simple context manager:
class ManagedResource:
def __enter__(self):
print("Resource acquired")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Resource released")
with ManagedResource() as resource:
print("Working with resource")
Here, with calls __enter__ upon entry and __exit__ upon exit from the block, ensuring proper resource management.