with — Intermediate Examples
Wraps a block with a context manager for automatic setup/teardown
Nested and multiple context managers
Managing multiple resources.
python
class Connection: def __init__(self, name): self.name = name def __enter__(self): print(f" Connect to {self.name}") return self def __exit__(self, *args): print(f" Disconnect from {self.name}") # Multiple context managers with Connection("db") as db, Connection("cache") as cache: print(f"Using {db.name} and {cache.name}") print() # contextlib.contextmanager decorator from contextlib import contextmanager @contextmanager def timer(label): import time start = time.perf_counter() try: yield finally: elapsed = time.perf_counter() - start print(f"{label}: {elapsed:.6f}s") with timer("Sum"): total = sum(range(1_000_000)) print(f"Total: {total}")
Multiple context managers can be combined in one with statement. @contextmanager makes writing context managers easy using yield.
Want to try these examples interactively?
Open Intermediate Playground