Context Managers in Python

What is a Context Manager?

A context manager is a Python construct that allows setup and cleanup actions around a block of code using the with statement. It ensures resources like files or network connections are properly managed and released.

Basic Syntax

with expression [as variable]:
    # code block

Examples

# 1. Using context manager to open a file
with open('example.txt', 'w') as f:
    f.write('Hello, World!')
# File is automatically closed after this block
  
# 2. Custom context manager using a class
class MyContext:
    def __enter__(self):
        print("Entering the context")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Exiting the context")

with MyContext() as ctx:
    print("Inside the context")
  
# Output:
# Entering the context
# Inside the context
# Exiting the context
  
# 3. Custom context manager using contextlib
from contextlib import contextmanager

@contextmanager
def my_context():
    print("Before the block")
    yield
    print("After the block")

with my_context():
    print("Inside the block")
  
# Output:
# Before the block
# Inside the block
# After the block
  

Why Use Context Managers?