Skip to content
Streak:0Loading your progress…Sign in

Module 4 · Lesson 3 of 3

Generators, decorators & context managers

yield, functions that wrap functions, and with-blocks. ~35 min

Lesson notes

Generators: functions that yield values lazily
def chunks(items, size):
    for i in range(0, len(items), size):
        yield items[i:i + size]

list(chunks([1, 2, 3, 4, 5], 2))  # [[1, 2], [3, 4], [5]]
Decorators: @decorator is sugar for fn = decorator(fn)
import functools, time

def timed(fn):
    @functools.wraps(fn)          # keep fn's name/docstring
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return fn(*args, **kwargs)
        finally:
            print(f"{fn.__name__} took {time.perf_counter() - start:.3f}s")
    return wrapper

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. 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. 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