Parametrised & class-based decorators

P29.decorators.02 · Audience: guest, it-ml, language-pro · Prerequisites: Decorators from scratch

Real LLM grading for this pageLLM grading (this page):

@retry(3) has parentheses — so it is not a decorator, it is a call that returns one. This module adds the two shapes production code leans on: decorator factories (parametrised) and class-based decorators, plus the stacking and method subtleties that come with them.

Step 1 / 4Factories: a decorator with settings
ⓘ Concept: retry(3) runs first
In @retry(3), the call retry(3) executes before any decorating: it must return a decorator. Hence three nested layers — factory(settings) returns decorator(func) which returns wrapper(*args). The factory runs once per decoration; the wrapper runs on every call, with the settings captured in its closure.

Why it matters — Nearly every library decorator you use — @app.route, @pytest.mark.parametrize, @lru_cache(maxsize=...) — is a factory; reading the three layers is the difference between copying recipes and writing them.

Ask the mentor about this module

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.

Ctrl/Cmd + Enter to send

🎓 Practice ladder

3 graded rungs · ~30 min

Your turn: build the @retry(times) factory, then a class-based @Once, and close with the interview walkthrough of the whole decorator machinery.

Rung 1 — a @retry(times) decorator factory

Loading exercise…

Rung 2 — a class-based @once decorator

Loading exercise…

Interview rung — decorators, stacking and factories (free-form)

Loading exercise…

By the end you should be able to sketch factory -> decorator -> wrapper on a whiteboard and say which layer runs when — the exact follow-up interviewers reach for after "write me a decorator".

Where next?