with — Intermediate Playground
Wraps a block with a context manager for automatic setup/teardown
Python Playground
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}")
Output
Click "Run" to execute your code
Multiple context managers can be combined in one with statement. @contextmanager makes writing context managers easy using yield.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?