FastAPI's @app.get("/"), pytest's @pytest.fixture, and agent frameworks' @tool are all decorators. Context managers (with open(path) as f:) guarantee cleanup — the Python equivalent of try/finally or Dart's using patterns.
Context managers via contextlib
from contextlib import contextmanager
@contextmanager
def transaction(db):
db.begin()
try:
yield db
db.commit()
except Exception:
db.rollback()
raise
Practice
1. A retry decorator
hard50 XP
Write retry(times, exceptions=(Exception,)) — a decorator *factory*. The wrapped function is called up to times attempts; if it raises one of exceptions, try again; after the last attempt re-raise. Other exceptions propagate immediately. Preserve the function name with functools.wraps. (No sleeping — we'll add backoff in the async module.)
Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor
2. Lazy batching generator
medium25 XP
Write a generator batched(iterable, size) that yields lists of up to size items from *any* iterable (including infinite generators) without converting it to a list first. Raise ValueError if size < 1.
Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor