Sobes.tech
Middle

What is a context manager, what tasks does it solve, and how to write your own using a class and a decorator?

sobes.tech AI

Answer from AI

A context manager in Python is an object that manages resources, ensuring their proper opening and closing. It is used with the with statement, which guarantees the execution of cleanup code even if exceptions occur.

Tasks of a context manager:

  • Automatic release of resources (files, connections, locks)
  • Ensuring code cleanliness and preventing resource leaks

Example implementation via a class:

class MyContextManager:
    def __enter__(self):
        print("Resource opened")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Resource closed")
        # You can handle exceptions here if needed

with MyContextManager() as cm:
    print("Working with resource")

Example implementation using the contextlib.contextmanager decorator:

from contextlib import contextmanager

@contextmanager
def my_context():
    print("Resource opened")
    try:
        yield
    finally:
        print("Resource closed")

with my_context():
    print("Working with resource")

Both approaches allow convenient resource management and ensure cleanup code execution.