Sobes.tech
Junior — Middle

How is the context manager mechanism implemented in Python?

sobes.tech AI

Answer from AI

In Python, the context manager mechanism is implemented using the __enter__ and __exit__ methods in a class. A context manager allows automatic management of resources, such as opening and closing files, setting and releasing locks.

Example of implementing a 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  # suppresses the exception

with MyContextManager() as cm:
    print("Inside with")
    # You can raise an exception to test __exit__
    # raise ValueError("Error")

Additionally, you can use the @contextmanager decorator from the contextlib module to create context managers based on generators.