Navigation

Python

How to Use Context Managers with "with" Statement

Use Python context managers with 'with' statement for automatic resource cleanup. Handle files, database connections, and locks safely.

Table Of Contents

Problem

You need to ensure resources like files, database connections, or locks are properly cleaned up even if errors occur.

Solution

# File handling with context manager
with open('data.txt', 'r') as file:
    content = file.read()
    print(content)
# File automatically closed, even if error occurs

# Multiple files
with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile:
    data = infile.read()
    outfile.write(data.upper())

# Custom context manager with class
class DatabaseConnection:
    def __enter__(self):
        print("Connecting to database...")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Closing database connection...")
        return False  # Don't suppress exceptions

with DatabaseConnection() as db:
    print("Using database")
    # Connection automatically closed

# Context manager with contextlib
from contextlib import contextmanager

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

with timer():
    import time
    time.sleep(1)
    print("Doing work...")

# Suppress specific exceptions
from contextlib import suppress

with suppress(FileNotFoundError):
    with open('nonexistent.txt') as f:
        content = f.read()
# No error thrown if file doesn't exist

# Lock example
import threading

lock = threading.Lock()
with lock:
    # Critical section code
    print("Thread-safe operation")
# Lock automatically released

Explanation

Context managers ensure cleanup code runs via __enter__ and __exit__ methods. The with statement guarantees __exit__ executes even if exceptions occur.

Use @contextmanager decorator for simple cases, or implement __enter__/__exit__ methods for complex resource management.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Python