Sub topic 4
Your first decorator
A decorator is a function that takes a function and returns a function. This chapter builds one from scratch using ordinary function calls. It uses no special syntax, because the @ shorthand comes in the next chapter.
Prerequisites
This chapter assumes you can do the following:
- Define and call Python functions, including positional and keyword arguments.
- Read a nested function and follow how an inner function uses a variable from the function around it (a closure).
- Use
*argsand**kwargsto collect and forward arguments.
What a decorator does
A decorator adds behavior around an existing function. The behavior might be logging, timing, caching, or a permission check. The original function body stays unchanged.
The mechanism has three steps:
- The decorator receives the original function as its argument.
- It defines a new inner function, usually called
wrapper, that runs extra code and calls the original. - It returns
wrapper. You then bind the original name to that returned function.
After that, every call to the original name runs the wrapper.
The smallest possible decorator
This version works only for functions that take no arguments.
def announce(func):
def wrapper():
print("before")
result = func()
print("after")
return result
return wrapper
def hello():
print("hello")
return 1
hello = announce(hello)
value = hello()
print(value)The output is:
before
hello
after
1announce(hello) runs once. It returns wrapper, a closure that remembers func, which here is the original hello. The line hello = announce(hello) rebinds the name hello to the wrapper. The original function is still alive because the wrapper holds a reference to it.
Two details matter:
- The wrapper stores the result in
resultand returns it. If you drop thereturn, the caller getsNone. announceruns once, when you apply it.wrapperruns on every call.
Forwarding arguments and return values
A decorator that works for only one signature is not much use. A general wrapper accepts anything and passes it through unchanged. You do that with *args and **kwargs.
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__} with args={args} kwargs={kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result!r}")
return result
return wrapper
def add(a, b=0):
return a + b
add = log_calls(add)
total = add(2, b=3)
print(total)The output is:
calling add with args=(2,) kwargs={'b': 3}
add returned 5
5*args collects the positional arguments into a tuple. **kwargs collects the keyword arguments into a dict. The call func(*args, **kwargs) unpacks both again, so add receives exactly what the caller sent. Because the wrapper accepts any arguments, the same decorator works on functions with different signatures.
The pattern has three parts, and a decorator is usually correct when it has all three:
- The wrapper accepts
*args, **kwargs. - It calls the original with
func(*args, **kwargs). - It returns whatever the original returned.
Decoration time versus call time
New decorator authors often confuse when code runs. Code in the outer function runs once, when the decorator is applied. Code in wrapper runs on every call.
def noisy(func):
print(f"decorating {func.__name__}")
def wrapper(*args, **kwargs):
print(f"running {func.__name__}")
return func(*args, **kwargs)
return wrapper
def f():
return "x"
f = noisy(f)
print("defined")
f()
f()The output is:
decorating f
defined
running f
running fdecorating f appears once, before defined. running f appears once for each call. This distinction matters when you design a decorator. Setup work, such as creating a dictionary or opening a resource, belongs in the outer function. Per-call work belongs in the wrapper.
Variables defined in the outer function are shared by every call to that wrapper. This is how decorators keep state, and it is also a source of surprises, covered below.
The wrapper decides whether to call the original
The wrapper is ordinary code, so it controls the call. It can run the original once, several times, or not at all. It can also change the arguments or the result.
This decorator refuses to call the original unless every positional argument is a positive number.
def ensure_positive(func):
def wrapper(*args, **kwargs):
for value in args:
if value <= 0:
raise ValueError(f"{func.__name__}: expected positive, got {value}")
return func(*args, **kwargs)
return wrapper
def square_root(x):
return x ** 0.5
square_root = ensure_positive(square_root)
print(square_root(16)) # 4.0
try:
square_root(-4)
except ValueError as error:
print(error) # square_root: expected positive, got -4The check runs before the original, so square_root(-4) never reaches the original function. This pattern underlies access checks, input validation, and caching. A cache returns a stored result and skips the call.
Doing work after the call, even on errors
Suppose a decorator measures time or releases a resource. The code after the call must still run when the original raises an exception. A plain statement after func(...) is skipped in that case. Use try and finally.
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.4f}s")
return wrapper
def divide(a, b):
return a / b
divide = timer(divide)
print(divide(10, 4))
try:
divide(1, 0)
except ZeroDivisionError:
print("caught")Both calls print a timing line. The second prints it and then lets ZeroDivisionError propagate to your except block. The finally clause runs after the return expression has been evaluated and before the function actually returns. It also runs when an exception is passing through.
Do not swallow exceptions inside a wrapper unless that is the purpose of the decorator. A wrapper that catches everything and returns None hides bugs from the caller.
A decorated function is a different object
After hello = announce(hello), the name hello points at wrapper. You can check this:
def announce(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def hello():
"""Say hello."""
return "hello"
print(hello.__name__) # hello
print(hello.__doc__) # Say hello.
hello = announce(hello)
print(hello.__name__) # wrapper
print(hello.__doc__) # NoneThe wrapper is a different function with its own __name__ and __doc__. Tracebacks, help(), and debuggers now show wrapper where you expected hello. The chapter on functools.wraps fixes this. For now, remember that a decorator replaces the function. It does not modify it.
Common mistakes in a first decorator
| Mistake | Symptom | Fix |
|---|---|---|
| Wrapper does not `return` the result | Decorated function returns `None` | Return `func(*args, **kwargs)` or the stored result |
| Decorator does not `return wrapper` | The name becomes `None`; calling it raises `TypeError: 'NoneType' object is not callable` | End the decorator with `return wrapper` |
| Writing `return wrapper()` | The wrapper runs at decoration time and the name gets its result | Return the function itself, with no parentheses |
| Wrapper has a fixed signature such as `def wrapper(x)` | `TypeError` when the function is called with other arguments | Accept `*args, **kwargs` and forward them |
| Calling `func` instead of passing it on, as in `announce(hello())` | The decorator receives the function's return value, not the function | Pass the function object: `announce(hello)` |
The last row is the most common source of confusing errors. hello is the function. hello() is the result of calling it. A decorator needs the function.
Reusing a decorator
One decorator can wrap many functions. Each call to the decorator creates a new closure with its own func.
def log_calls(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
print(f"{func.__name__}{args} -> {result!r}")
return result
return wrapper
def add(a, b):
return a + b
def shout(text):
return text.upper()
add = log_calls(add)
shout = log_calls(shout)
add(1, 2) # add(1, 2) -> 3
shout("hey") # shout('hey') -> 'HEY'The two wrappers do not interfere. Each remembers its own original.
You can also apply a decorator to a function without keeping the original name. result = log_calls(add)(1, 2) builds a wrapper, calls it once, and discards it. This is rarely useful, but it shows that a decorator call is a plain function call.
How to check your decorator
Before using a new decorator, test these four things:
- It works with positional arguments, keyword arguments, and a mix of both.
- The return value passes through. Compare
decorated(x)with the original's result. - An exception raised by the original reaches the caller.
- The decorator can wrap two different functions without them sharing state by accident.
Exercise
Write a decorator double_result that returns twice the value the wrapped function returns. Apply it by reassignment to def add(a, b): return a + b, then state what add(2, 3) returns and what happens if you leave out return in the wrapper.
Show answer
def doubleresult(func): def wrapper(args, kwargs): return func(args, *kwargs) 2 return wrapper add = doubleresult(add) add(2, 3) returns 10. If the wrapper computes the value but does not return it, the call returns None, because a function without a return statement returns None.
Exercise
A student writes def deco(func): return func() and then runs hello = deco(hello). What goes wrong, and what should the decorator return instead?
Show answer
func() calls the original function immediately, at decoration time, so hello is bound to the function's result rather than to a function. Calling hello() then fails or misbehaves. The decorator should define and return a wrapper function, and the wrapper should call func(*args, **kwargs) when it is invoked.