Explain it simply
Explain it simply
In the earlier decorator lesson you wrapped a function in one layer. Now picture a factory that makes wrapping paper to order: say "red, with three ribbons" and it produces paper with exactly those settings. @retry(times=3) is the same kind of order: "make me a decorator that tries three times".
A present can also be wrapped in several layers, and opening it means removing the outermost layer first. Stacking decorators works the same way. Some wrappings even need a small notebook attached to record how many times the present was opened; that is a class-based decorator.
Problem → Why → Solution
The problem: one decorator per setting
Say you have a decorator that retries a failed network call. Then requirements arrive: the payment API should be retried three times and the email service five. A plain decorator receives only func, so you end up with retry_3 and retry_5, two full copies that differ by a single number. Needing ten attempts means a third copy.
def retry_3(func):
def wrapper(*args, **kwargs):
for _ in range(3): # the only difference...
try:
return func(*args, **kwargs)
except ConnectionError:
pass
return wrapper
def retry_5(func): # ...copied again with range(5)
...
@retry(5) # what we want: TypeError, retry is not written to take a numberWhy can't the number just be passed in?
The @ line evaluates the expression to its right and calls the result with the decorated function. With @retry(5), retry(5) runs first, and whatever it returns must be a decorator. So you need one more function layer that accepts the setting and returns the decorator, which is called a decorator factory.
Core concept: functions that build decorators, and layers of them
A decorator factory has three nested functions. The outer retry(times) accepts the setting and returns a decorator; the middle decorator(func) accepts the function and returns a wrapper; the inner wrapper(*args, **kwargs) runs on every call. @retry(times=3) is the same as read_sensor = retry(times=3)(read_sensor). Thanks to two levels of closure, the wrapper can see both times and func.
When decorators are stacked, the one closest to the function, at the bottom, is applied first. Writing @tag("b") above @tag("i") gives title = tag("b")(tag("i")(title)). At call time, though, the outermost wrapper runs first and calls inward, and the result travels back out, producing <b><i>hi</i></b>. The order matters: put @cache outside @require_login and cached results can be returned without the login check ever running.
Any callable object can be a decorator, not just a function. In a class-based decorator, __init__(self, func) runs once at definition time and stores the function, while __call__ runs on every call. Instance attributes give a clear home for state such as a call count, a cache or a rate-limit timestamp. Because @functools.wraps cannot be applied to a class this way, __init__ calls functools.update_wrapper(self, func) to copy the name and docstring.
Decorating a method in a class with a function decorator just works. The wrapper is an ordinary function, so when it is accessed through an instance Python turns it into a bound method, and self arrives as the first element of *args. A class-based decorator is different: plain instances have no __get__, so no bound method is created and self is lost. The deeper section shows the fix. For a decorator meant to sit on methods, a closure-based function decorator is therefore the simplest choice.
- factory(setting) returns a decorator
- The bottom decorator is applied first
- A call enters the outermost wrapper
- Results travel back from the inside
Parentheses on the @ line mean a factory is called first; no parentheses means the decorator itself.
General pattern
def factory(setting): # runs once, on the @ line
def decorator(func): # receives the function
@functools.wraps(func)
def wrapper(*args, **kwargs): # runs on every call
... # use setting and func
return wrapper
return decorator
class Decorator:
def __init__(self, func): ... # once, at definition time
def __call__(self, *args, **kwargs): ... # every callA factory has three layers and remembers setting and func through closures. In a class-based decorator, __init__ stores the function and __call__ runs on every call.
Example: a retry factory, stacking, a class decorator and a method
The readings iterator gives two bad values before "42", so you can watch retry at work. Notice that the "attempt" lines appear above "1. factory:": print() evaluates its argument, read_sensor(), before it prints anything.
import functools
# 1. A decorator factory: retry(times=3) RETURNS the real decorator
def retry(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except ValueError as err:
print(f" attempt {attempt} failed: {err}")
raise RuntimeError(f"{func.__name__} failed {times} times")
return wrapper
return decorator
def tag(name):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return f"<{name}>{func(*args, **kwargs)}</{name}>"
return wrapper
return decorator
# 2. A class-based decorator keeps state on the instance
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
readings = iter(["n/a", "err", "42"])
@retry(times=3)
def read_sensor():
value = next(readings)
if not value.isdigit():
raise ValueError(f"bad reading {value!r}")
return int(value)
print("1. factory:", read_sensor())
@tag("b")
@tag("i")
def title(text):
return text
print("2. stacked:", title("hi"))
@CountCalls
def ping():
return "pong"
ping()
ping()
print("3. class-based:", ping.__name__, ping.calls)
# 4. Function decorators work on methods: self arrives inside *args
class Card:
def __init__(self, owner):
self.owner = owner
@tag("p")
def render(self):
return f"card of {self.owner}"
print("4. method:", Card("Mya").render())Code breakdown
- Line 5-16
def retry(times):The outer function accepts only times and returns the decorator. Inside the wrapper, the loop prints a message on each ValueError and tries again, leaving immediately through return on success. If every attempt fails, it raises RuntimeError.
- Line 42-43
@retry(times=3)Python calls retry(times=3) first, then wraps read_sensor with the decorator it returns. Leaving out the parentheses, @retry, would make the read_sensor function itself become times.
- Line 52-57
@tag("i")tag("i") wraps title first and tag("b") wraps that result. A call enters the b wrapper, then the i wrapper, then title, giving <b><i>hi</i></b>. Swap the two lines and you get <i><b>hi</b></i>.
- Line 29-37
functools.update_wrapper(self, func)@CountCalls means ping = CountCalls(ping), so the name ping now refers to an instance. update_wrapper keeps ping.__name__ as "ping", and self.calls += 1 inside __call__ counts every call.
- Line 70-78
def render(self):tag's wrapper is a plain function, so Card("Mya").render becomes a bound method and the instance arrives as args[0]. The wrapper forwards it to render, which can then read self.owner.
attempt 1 failed: bad reading 'n/a'
attempt 2 failed: bad reading 'err'
1. factory: 42
2. stacked: <b><i>hi</i></b>
3. class-based: ping 2
4. method: <p>card of Mya</p>- The name title is tag("b")'s wrapper, so it runs first
- The b wrapper calls the inner tag("i") wrapper
- The i wrapper calls the original title("hi") and gets "hi"
- The i wrapper returns "<i>hi</i>"
- The b wrapper returns "<b><i>hi</i></b>" to the caller
Making a class-based decorator work on methods with __get__
Put the CountCalls above on a method and call Greeter().hello("Aye"), and you get TypeError: "Greeter.hello() missing 1 required positional argument: 'name'". The instance is never passed as self, so "Aye" lands in the self slot and name goes missing. Functions are descriptors: reading one through an instance calls __get__, which returns a bound method. Give your class a __get__ that binds the instance with types.MethodType and the problem is solved.
import functools
import types
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
def __get__(self, instance, owner):
if instance is None: # accessed on the class itself
return self
return types.MethodType(self, instance) # bind like a method
class Greeter:
@CountCalls
def hello(self, name):
return f"hello {name}"
g = Greeter()
print(g.hello("Aye"), g.hello("Sai")) # hello Aye hello Sai
print("calls:", Greeter.hello.calls) # calls: 2Who shares the state?
There is one decorator instance per decorated function. On a method, every Greeter object shares that single calls counter; to count per object, store the state on the instance instead.
In real projects
Where this shows up in real projects
Frameworks are full of decorator factories. Flask's @app.route("/users", methods=["POST"]), pytest's @pytest.mark.parametrize("n", [1, 2, 3]) and functools' @lru_cache(maxsize=128) all take arguments first and return a decorator. Retry libraries such as Tenacity follow the same pattern with settings like @retry(stop=stop_after_attempt(3)).
Stacking order causes real production bugs. In Flask, @app.route must sit on top so that it registers the function already wrapped by @login_required below it. Swap them and the unprotected function is registered as the route, skipping authentication entirely. Class-based decorators show up where state must persist between calls, such as rate limiters and circuit breakers.
Teams often share decorator factories as an internal library: @audit(action="refund") writes an audit row to the database, @feature_flag("new_checkout") falls back to the old function when the flag is off, and @timeout(seconds=5) cuts off calls that run too long. When reviewing decorators like these, check that they use wraps, that they do not swallow exceptions, and that their docstring says where they belong in a stack.
Common mistakes
Common mistakes
1. Using a factory without parentheses
Writing @retry makes it retry(read_sensor): times becomes the function and you get back the decorator, not a wrapper. Calling read_sensor() then raises a TypeError, because decorator() receives no func. Write @retry() even when using defaults, or deliberately design a decorator that accepts both forms.
2. Stacking in the wrong order
With @timed below @retry(times=3), each attempt is timed separately; with it above, you time all attempts together. With security concerns such as authentication and caching, the wrong order can skip the check entirely. Read a stack from the bottom up and ask which decorator wraps which.
3. Using a class-based decorator on a method without __get__
A class decorator that works fine on functions fails on a method with "missing 1 required positional argument", because self never arrives. If it will be used on methods, add __get__, or rewrite it as a function decorator with a closure.
4. Sharing mutable state from the factory across functions
If cache = {} lives in the factory rather than inside decorator(), then calling the factory once and reusing the result on many functions (shared = cached(); @shared ...) makes every function share one dict, and their results get mixed up. Create per-function state inside the decorator(func) layer.
Mini challenge
Mini challenge: a role-checking decorator factory
Write a require_role(role) factory that raises PermissionError instead of running the function when the user lacks the role. Then stack it with a log_calls decorator and try it with an admin user and a guest user.
- require_role(role) returns a decorator whose wrapper takes the user dict as its first argument
- If role is not in user["roles"], raise PermissionError mentioning the user's name
- log_calls sits above @require_role, so blocked calls are logged too
- Both wrappers use functools.wraps, so __name__ stays delete_post
import functools
def log_calls(func):
# TODO: wrapper that prints "[log] <name> called" and forwards the call
...
def require_role(role):
# TODO: return a decorator
# its wrapper(user, *args, **kwargs) checks role in user["roles"]
# missing role -> PermissionError(f"{user['name']} needs role {role!r}")
...
# TODO: stack @log_calls above @require_role("admin") on delete_post(user, post_id)
# returning f"post {post_id} deleted by {user['name']}"
admin = {"name": "Aye", "roles": ["admin", "editor"]}
guest = {"name": "Sai", "roles": ["reader"]}
# TODO: call it for admin (post 7), call it for guest (post 8) inside try/except,
# then print delete_post.__name__Expected: [log] delete_post called post 7 deleted by Aye [log] delete_post called blocked: Sai needs role 'admin' name kept: delete_post
Show hint
Writing the wrapper as def wrapper(user, *args, **kwargs) lets you read user by name and forward the rest through *args. Because log_calls is on top, its log line prints even when require_role raises.
Show solution
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"[log] {func.__name__} called")
return func(*args, **kwargs)
return wrapper
def require_role(role):
def decorator(func):
@functools.wraps(func)
def wrapper(user, *args, **kwargs):
if role not in user["roles"]:
raise PermissionError(f"{user['name']} needs role {role!r}")
return func(user, *args, **kwargs)
return wrapper
return decorator
@log_calls
@require_role("admin")
def delete_post(user, post_id):
return f"post {post_id} deleted by {user['name']}"
admin = {"name": "Aye", "roles": ["admin", "editor"]}
guest = {"name": "Sai", "roles": ["reader"]}
print(delete_post(admin, 7))
try:
delete_post(guest, 8)
except PermissionError as err:
print("blocked:", err)
print("name kept:", delete_post.__name__)Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A decorator with arguments has three layers, factory, decorator and wrapper; @factory(x) equals factory(x)(func).
- In a stack, the bottom decorator is applied first, and at call time the outermost wrapper runs first.
- A class with __init__ and __call__ is a stateful decorator; copy metadata with update_wrapper.
- Function decorators work on methods, but a class-based decorator needs __get__.
Python Documentation — Functional Programming HOWTO — Python Software Foundation