pythonintermediate
contextlib Utilities for Resource Management
Use contextlib for lightweight context managers, suppressing exceptions, and redirect output.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonintermediate
Python Context Manager Patterns
Create custom context managers with __enter__/__exit__ and contextlib for resource management.
Best for: Automatic resource cleanup and lifecycle management
#python#context-manager
pythonintermediate
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.
Best for: Database connection management
#context-manager#resource-management
pythonintermediate
Custom Context Manager with __enter__ / __exit__
Build reusable resource management with Python context managers.
Best for: Resource cleanup
#python#context-manager
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation