Sobes.tech
Junior — Middle

How can you implement a custom context manager in a Python class?

sobes.tech AI

Answer from AI

To implement a custom context manager in Python, you need to define a class with __enter__ and __exit__ methods.

  • __enter__(self) is called when entering the with block and can return an object that will be accessible inside the block.
  • __exit__(self, exc_type, exc_val, exc_tb) is called when exiting the with block, where you can handle exceptions or perform cleanup.

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"Handling exception: {exc_val}")
        return True  # suppresses the exception

with MyContextManager() as manager:
    print("Inside with block")
    # You can raise an error for testing
    # raise ValueError("Error")

This manager allows managing resources, such as opening and closing files, setting and releasing locks, etc.