Sobes.tech
Middle

How to implement a context manager yourself? What methods need to be implemented?

sobes.tech AI

Answer from AI

In Python, a context manager is an object that implements the __enter__ and __exit__ methods.

  • __enter__(self) is called when entering the with block. It usually returns the resource or the object itself.
  • __exit__(self, exc_type, exc_val, exc_tb) is called when exiting the with block. It receives information about the exception if one occurred, or None.

Example of implementing a simple 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"Handled exception: {exc_type}")
        return False  # do not suppress exceptions

with MyContextManager() as cm:
    print("Inside with block")
    # you can raise an error to test __exit__
    # raise ValueError("Error")

Thus, to create a context manager, you need to implement the __enter__ and __exit__ methods.