Decorators from scratch
P29.decorators.01 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Closures & first-class functions
Where next?
Later in Decorators
P29.decorators.01 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Closures & first-class functions
Later in Decorators
A decorator looks like magic syntax, but it is nothing more than the closure
machinery you just built, pointed at a function. This module strips the
@ sign down to what actually runs, then rebuilds the two classics —
a call counter and a memoiser — from scratch.
@count_calls above def greet(...) is executed once, at definition time, as greet = count_calls(greet). The decorator receives the function object and returns a replacement — usually an inner wrapper that does something extra and then calls the original. Define, wrap, return: that is the whole trick.Why it matters — Once you read the @ sign as plain assignment, every decorator — logging, caching, retrying, auth — is the same three-line shape, and none of it is magic.
Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.
Off by default. The mentor always gets your file; this only decides whether your own copy stays here. Copies live in this browser only - they do not follow you to another device, and clearing site data removes them.
Your turn: write @count_calls with
functools.wraps, then rebuild @memoize — the
hand-rolled heart of lru_cache.
Loading exercise…
Loading exercise…
By the end, @anything should read as ordinary code to you: a function call
at definition time that swaps in a wrapper you could have written yourself.
Loading your notes...