Skip to main content Brad's PyNotes

PEP 343: The 'With' Statement - Context Management Done Right

TL;DR

PEP 343 introduced the ‘with’ statement for automatic resource management, ensuring cleanup code runs even when exceptions occur, making file handling and resource management safer and cleaner.

Interesting!

The with statement implements the context manager protocol, automatically calling enter and exit methods, which means you never forget to close files or release resources.

Automatic Resource Management

python code snippet start

# File handling - automatic closing
with open('data.txt', 'r') as file:
    content = file.read()
    # File automatically closed, even if exception occurs

# Multiple context managers
with open('input.txt') as infile, open('output.txt', 'w') as outfile:
    outfile.write(infile.read().upper())

python code snippet end

Creating Custom Context Managers

python code snippet start

from contextlib import contextmanager

@contextmanager
def timer():
    import time
    start = time.time()
    try:
        yield
    finally:
        print(f"Elapsed: {time.time() - start:.2f}s")

# Usage
with timer():
    time.sleep(1)  # Elapsed: 1.00s

python code snippet end

The with statement guarantees cleanup code execution, making Python programs more robust and preventing resource leaks. Use with database connections and thread locks for safe resource management. The pattern complements exception handling and enables pathlib file operations .

Reference: PEP 343 - The “with” Statement