Advanced Python: decorators, functools, and closures
Closures, simple decorators, functools.wraps, partial, and lru_cache in Python, plus the order they apply. Twenty exercises with fold-out solutions.
Getting started
Home Assistant
Buying
Closures, simple decorators, functools.wraps, partial, and lru_cache in Python, plus the order they apply. Twenty exercises with fold-out solutions.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
Direct answer (November 2026) — A decorator is a function that wraps another function to add behavior (a trace, a cache, validation). The syntax
@decorabovedefis the same asf = decor(f). Usefunctools.wrapsto keep the original function’s name and docstring.
This lesson follows the advanced Python course after generators and before context managers. Hub: programming.

A decorator is a function that takes a function (or a class) and returns an enriched stand-in: logging, timing, argument validation, caching, and so on. It is syntactic sugar: @decor above def f is the same as f = decor(f) (as a first approximation). Combined with the functools module (Python’s standard library), you get reusable patterns without copying and pasting.
An inner function can capture variables from the enclosing scope: that is a closure. Useful when you parameterize a decorator (def decorateur(prefixe): ... def wrapper(f): ...).
def tracer(f):
def wrapper(*args, **kwargs):
print("call", f.__name__)
return f(*args, **kwargs)
return wrapper
@tracer
def add(a, b):
return a + b
Without @, you would write add = tracer(add).
functools.wrapsThe wrapper replaces f and often loses __name__, __doc__, and the annotations. @functools.wraps(f) on def wrapper copies those metadata — essential for introspection and for the docs that tools show.
functools.partialpartial(func, *args, **kwargs) “freezes” part of the arguments to create a new callable with the remaining arguments — handy when you adapt an API to a callback.
from functools import partial
basetwo = partial(int, base=2)
basetwo("10010") # 18
functools.lru_cache@lru_cache(maxsize=128) remembers the results of a pure function (same inputs → same output) so you do not recompute them. Useful for recursion such as Fibonacci or for expensive parsers — watch the memory use and unhashable arguments.
Exercise 1 — Rewrite @tracer without @: assign add = tracer(add) after def add. Easy
def tracer(f): def wrapper(*a, **k): print("call", f.__name__) return f(*a, **k) return wrapperdef add(a, b): return a + b
add = tracer(add)
Exercise 2 — Import wraps and decorate the wrapper so it keeps __name__ from f. Easy
from functools import wraps
def tracer(f): @wraps(f) def wrapper(*a, **k): print(“call”, f.name) return f(*a, **k) return wrapper
Exercise 3 — Use partial to create mul3 = partial(operator.mul, 3) (import operator). Easy
import operator
from functools import partial
mul3 = partial(operator.mul, 3)
print(mul3(4))
Exercise 4 — Apply @lru_cache to a naive recursive fib(n) and compare the time for n=35 (hint: without the cache, it is very slow). Easy
from functools import lru_cache@lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n - 1) + fib(n - 2)
print(fib(35))
Exercise 5 — What happens if you stack @a then @b above def f? (application order). Easy
# @a @b def f → f = a(b(f)): b is applied first, then a.
Exercise 6 — A parameterized decorator retry(n) that tries again n times if an Exception is raised — a skeleton is fine. Easy
from functools import wraps
def retry(n): def deco(f): @wraps(f) def wrapper(*a, **k): for _ in range(n): try: return f(*a, **k) except Exception: pass return f(*a, **k) return wrapper return deco
Exercise 7 — lru_cache: why must the arguments be hashable? Easy
# The cache uses an internal dict; keys are argument tuples and must be hashable.
Exercise 8 — A timer decorator with time.perf_counter that prints how long the call took. Intermediate
import time from functools import wraps
def timer(f): @wraps(f) def wrapper(*a, **k): t0 = time.perf_counter() out = f(*a, **k) print(time.perf_counter() - t0) return out return wrapper
Exercise 9 — Use partial to bind open in mode "r" with encoding="utf-8". Intermediate
from functools import partial
open_utf8 = partial(open, mode="r", encoding="utf-8")
Exercise 10 — The difference between @staticmethod and @classmethod (a reminder): when do you use each inside a class? Intermediate
# staticmethod: no self/cls. classmethod: first argument is the class; alternative constructors, parsers.
Exercise 11 — A minimal class decorator that adds an attribute _tag = "ok" to the class. Intermediate
def tag(cls): cls._tag = "ok" return cls
@tag class Foo: pass
Exercise 12 — Why wrapper(*args, **kwargs) rather than wrapper() in a generic decorator? Intermediate
# So you can forward any signature to the decorated function.
Exercise 13 — lru_cache(maxsize=2): what happens when a 3rd distinct result is requested (eviction policy)? Intermediate
# LRU: the least recently used entry is evicted (an approximation, depending on the implementation).
Exercise 14 — Use functools.reduce to sum [1, 2, 3, 4] with operator.add. Intermediate
import operator
from functools import reduce
print(reduce(operator.add, [1, 2, 3, 4], 0))
Exercise 15 — A typed decorator that checks positional arguments against simple annotations (int, str) — a minimal version for 2 parameters. Hard
from functools import wraps
def typed(f): ann = f.annotations @wraps(f) def wrapper(a, b): if not isinstance(a, ann.get(“a”, type(a))): raise TypeError if not isinstance(b, ann.get(“b”, type(b))): raise TypeError return f(a, b) return wrapper
Exercise 16 — Implement singledispatch on the first argument for show(x), with int and str branches. Hard
from functools import singledispatch@singledispatch def show(x): return f”other {x}”
@show.register def _(x: int): return f”int {x}”
@show.register def _(x: str): return f”str {x}”
Exercise 17 — The problem of a decorator that changes the signature shown by help(): which inspect tool or third-party library helps keep a signature you can display? (answer in one sentence). Hard
# functools.wraps helps; for complex signatures, inspect.signature or decorator.wraps (third-party).
Exercise 18 — A cache with cache_clear: call fib.cache_clear() after several fib(n) calls. Hard
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
...
fib.cache_clear()
Exercise 19 — An once decorator that guarantees a function with no arguments runs only once and remembers the result. Hard
def once(f):
r = []
@wraps(f)
def wrapper():
if not r:
r.append(f())
return r[0]
return wrapper
Exercise 20 — Explain why decorating a function that you rebind at runtime (f = new_f) can break references the decorator still holds — a pattern to avoid. Hard
# The wrapper may close over the old function; decorate again or import cleanly.
Context managers and contextlib: with, and clean setup/teardown.
Check today’s price on Amazon
Can a decorator take arguments? Yes: @retry(tries=3) often needs three levels of functions (factory → decorator → wrapper).
lru_cache on an instance method? Not recommended: the cache lives on the function, not per object — prefer an explicit cache or functools.cached_property.
Order of several @? Applied from the bottom up: @a @b def f → f = a(b(f)).
How is that different from a plain call f()? The decorator runs when the function is defined, not on every call — ideal for registering f in a Flask/FastAPI router or for adding a wrapper only once.
Next in the course — asyncio · advanced typing · decorators project journal · programming hub.
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).