1.3.8 · D3Python Intermediate

Worked examples — Decorators — function decorators, @, wraps

2,341 words11 min readBack to topic

This is the "run every case" companion to the parent Decorators note. Before we begin, one promise: every symbol here was earned in the parent. If you have not yet met first-class functions (functions you can pass around like numbers) or closures (an inner function remembering a variable from outside), pause and read First-class functions and Closures and free variables first.

We test a decorator by asking: when I put @deco above a def, does the name now point to a new function that still does the old job, plus the new one?


The scenario matrix

Think of a decorator as a machine with many dials: does the wrapped function take arguments? does it return a value? is the decorator itself parametrised? are decorators stacked? Each combination is a cell we must survive.

Cell Case class The tricky part
A No-arg function, no return Simplest wrapper — does @ even fire?
B Function with positional + keyword args *args, **kwargs forwarding
C Function returns a value Must return func(...) or lose it
D Metadata preserved @wraps vs the __name__ lie
E Parametrised decorator @repeat(3) Three nested layers, factory called first
F Stacked decorators @a @b Order = a(b(f)), bottom-up
G Degenerate input: @repeat(0) Loop runs zero times → what returns?
H Real-world word problem Caching an expensive call
I Exam twist: state between calls Closure counter, mutable via nonlocal

The nine examples below hit every cell. Each one asks you to forecast first — cover the answer and guess.











Recall Which cell did each example cover?

Cell A (no-arg fires) ::: Example 1 Cell B + C (args & return) ::: Example 2 Cell C failure (missing return → None) ::: Example 3 Cell D (@wraps vs __name__) ::: Example 4 Cell E (parametrised @repeat(n)) ::: Example 5 Cell G (degenerate @repeat(0)) ::: Example 6 Cell F (stacked order a(b(f))) ::: Example 7 Cell H (real-world cache) ::: Example 8 Cell I (stateful counter, nonlocal) ::: Example 9


Connections