advanced Estimated learning time: 4 h

2.12 Decorators and closures

You can add timing, caching or retries without touching a function's body.

Before:00. Orientation & SetupUnlocks:03. Data Handling & Analysis04. Classical AI — Agents, Search & Knowledge Representation

Decorators wrap behaviour — timing, caching, retries — around a function without editing its body, and frameworks ahead use them constantly for routes, fixtures and tool registration. Writing one from scratch demystifies the at-sign permanently. It sits here because it composes closures from earlier. The small omission with large consequences is functools.wraps; leave it out and the wrapped function loses its name and docstring, confusing every tool that introspects it.

Work through these

  • Functions as first-class objects

    Functions in Python are values that can be passed around and returned like anything else. This one fact is what makes everything else in this topic possible.

  • Writing a decorator with functools.wraps

    Wrapping a function to add behaviour before or after it, while preserving its name and description. The preservation step is small and frequently omitted.

  • Decorators with arguments

    A decorator that itself takes settings requires an extra layer of nesting, which is the part that reads confusingly the first few times. Working through one example makes it click.

  • lru_cache, retry and timing decorators

    Caching results, retrying on failure, and measuring how long something took, all added without editing the function being wrapped. These three cover most practical decorator use.

Sign in to keep your progress.

Free resources

Links last checked 29 Aug 2026.

Stuck here?

Ask a mentor. A real person answers, and they can see exactly which topic you're on. Usually within a couple of working days.

Checking your session…

Topics shown in module order.