Sobes.tech
Junior — Middle

What methods of implementing context managers in Python do you know?

sobes.tech AI

Answer from AI

In Python, there are two main ways to implement context managers:

  1. Using __enter__ and __exit__ methods in a class

    You need to define a class with methods:

    • __enter__(self) — called when entering the with block, returns an object that will be assigned to the variable after as.
    • __exit__(self, exc_type, exc_val, exc_tb) — called when exiting the block, where you can handle exceptions and free resources.

    Example:

    class MyContext:
        def __enter__(self):
            print('Enter')
            return self
        def __exit__(self, exc_type, exc_val, exc_tb):
            print('Exit')
    
    with MyContext() as ctx:
        print('Inside block')
    
  2. Using the @contextmanager decorator from the contextlib module

    Allows writing a generator where code before yield is the entry code, and code after yield is the exit code.

    Example:

    from contextlib import contextmanager
    
    @contextmanager
    def my_context():
        print('Enter')
        yield
        print('Exit')
    
    with my_context():
        print('Inside block')
    

Both methods are widely used in Python for resource management, such as working with files, locks, network connections, etc.