pythonintermediate

contextlib Utilities for Resource Management

Use contextlib for lightweight context managers, suppressing exceptions, and redirect output.

python
from contextlib import contextmanager, suppress, redirect_stdout, ExitStack
import io, os

@contextmanager
def timer(label: str):
    import time
    start = time.perf_counter()
    try:
        yield
    finally:
        elapsed = time.perf_counter() - start
        print(f"{label}: {elapsed:.3f}s")

with timer("data processing"):
    result = sum(range(1_000_000))

# suppress specific exceptions
with suppress(FileNotFoundError):
    os.remove("/tmp/might-not-exist.txt")

# Capture stdout
buf = io.StringIO()
with redirect_stdout(buf):
    print("captured!")
output = buf.getvalue()  # "captured!\n"

# ExitStack for dynamic context managers
def process_files(paths: list[str]) -> list[str]:
    with ExitStack() as stack:
        files = [stack.enter_context(open(p)) for p in paths]
        return [f.read() for f in files]

@contextmanager
def managed_db_transaction(db):
    conn = db.connect()
    try:
        yield conn
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()

Use Cases

  • timing code
  • resource cleanup
  • dynamic context managers

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.