How do I create and use context managers in Python?

In Python, context managers are used to manage resources efficiently. They allow you to allocate and release resources precisely when you want to. The most common way to create a context manager is by using the `with` statement. Context managers can be created using a class or by using the `contextlib` module.

Creating a Context Manager Using a Class

To create a context manager using a class, you need to implement the `__enter__` and `__exit__` methods.

class MyContextManager:
    def __enter__(self):
        print("Entering the context")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("Exiting the context")

# Using the context manager
with MyContextManager() as manager:
    print("Inside the context")

Creating a Context Manager Using contextlib

You can also create a context manager using the `contextlib` module, which provides a simpler way to do so by using the `@contextmanager` decorator.

from contextlib import contextmanager

@contextmanager
def my_context_manager():
    print("Entering the context")
    yield
    print("Exiting the context")

# Using the context manager
with my_context_manager():
    print("Inside the context")

Python context managers resource management with statement contextlib