Python Context Managers

Context managers provide a clean way to manage resources such as files, database connections, and locks. They automatically handle setup and cleanup.

Using the with Statement

The with statement automatically closes a file after the block finishes, even when an exception occurs.

Python
Safely read a file using a context manager.
with open("data.txt", "r") as file:
    content = file.read()
    print(content)

Create a Context Manager

A class can act as a context manager by implementing __enter__ and __exit__.

Python
Create a simple custom context manager.
class Manager:
    def __enter__(self):
        print("Started")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("Finished")

with Manager():
    print("Inside block")

__enter__ and __exit__

__enter__ runs when the with block starts. __exit__ runs when the block ends and can be used for cleanup or exception handling.

Using contextlib

The contextlib module provides utilities for creating context managers without defining a full class.

Python
Create a context manager with contextmanager.
from contextlib import contextmanager

@contextmanager
def resource():
    print("Start")
    try:
        yield
    finally:
        print("Cleanup")

with resource():
    print("Working")

Common Use Cases

Context managers are commonly used for files, database connections, locks, temporary resources, network connections, and transaction handling.

Why Use Context Managers?

They reduce cleanup code, make resource handling safer, and ensure cleanup happens consistently.

Summary

Python context managers use the with statement to manage resources safely. You can use built-in context managers, create classes with __enter__ and __exit__, or use contextlib.