Sub topic 4
Your first decorator
This chapter assumes you can define and call functions, use *args and **kwargs, and understand that a nested function can read variables from the function around it (a closure). The earlier chapters covered those ideas. Here you put them together.
What a decorator is
A decorator is a function that takes a function and returns a function. The returned function usually calls the original and adds behavior before or after the call. The original function's body is never edited.
A decorator has three parts:
- An outer function that receives the function to wrap, often named
func. - An inner function, the wrapper, that runs when the decorated name is called.
- A
returnof the wrapper, without calling it.
A working example
This decorator logs each call and its result:
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result!r}")
return result
return wrapper
def add(a, b):
return a + b
add = log_calls(add)
print(add(2, b=3))Running it prints:
calling add
add returned 5
5The line add = log_calls(add) is the decoration step. It runs log_calls once, with the original add as func. The result, wrapper, is bound to the name add. From then on, every add(...) call runs wrapper. The func variable stays alive inside the wrapper because of the closure. The next chapter shows a shorter way to write this line.
Why the wrapper uses *args and **kwargs
The decorator does not know which function it will wrap. Declaring the wrapper as wrapper(*args, **kwargs) makes it accept any call. It then passes everything to func unchanged.
Two details matter:
- Store the result of
func(...)and return it. A wrapper that skips this changes what the caller gets back. - Call
func(*args, **kwargs)with the stars. Without them, the wrapper passes the tuple and the dictionary as two plain arguments.
The same pattern, reused
The pattern works for any function, because the wrapper is generic. Here is a decorator that prints how long a call took:
import time
def timed(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
print(f"{func.__name__} took {time.perf_counter() - start:.4f}s")
return wrapper
def pause(seconds):
time.sleep(seconds)
return "done"
pause = timed(pause)
print(pause(0.1))The try/finally makes the timing line print even if func raises an exception. The exception still reaches the caller.
Common first mistakes
| Mistake | What happens |
|---|---|
| `return wrapper()` instead of `return wrapper` | The wrapper runs immediately, at decoration time. The name is bound to its result, not to a function. |
| Forgetting `return result` in the wrapper | Every call returns `None`. |
| Writing `func()` without forwarding arguments | Calls with arguments raise `TypeError`. |
| Forgetting `return wrapper` in the decorator | The name is bound to `None`. The next call fails with `'NoneType' object is not callable`. |
Exercise
Write a decorator double_result that calls the wrapped function with whatever arguments it was given and returns twice its result. Apply it to def total(a, b): return a + b by reassigning the name. What does total(1, 2) return?
Show answer
def doubleresult(func): def wrapper(args, kwargs): return func(args, *kwargs) 2 return wrapper def total(a, b): return a + b total = doubleresult(total) print(total(1, 2)) # 6 The wrapper forwards the arguments, so total(1, 2) computes 3 and the wrapper returns 6.