Sub topic 14
Common pitfalls and how to debug them
This chapter assumes you can write a basic decorator, use functools.wraps, and have seen decorator factories. Most decorator bugs come from a few mistakes. They are easy to fix once you know what each one looks like.
Pitfall 1: forgetting to call the factory
A decorator factory returns the real decorator. If you write @repeat instead of @repeat(times=3), Python passes your function to repeat as times.
import functools
def repeat(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat
def say(message):
print(message)
print(say.__name__) # decorator
print(say("hello")) # <function say at 0x...>Nothing fails at definition time. Here say is now the inner decorator function. Calling say("hello") passes "hello" as func, so it returns a wrapper and prints nothing. The clue is a decorated name that points to the wrong function. The fix is @repeat(times=3).
Pitfall 2: dropping the return value
A wrapper that calls the function but does not return its result makes every call return None.
def loud(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs) # missing return
return wrapper
@loud
def add(a, b):
return a + b
print(add(1, 2)) # NoneAlways write return func(*args, **kwargs), or store the result, do your extra work, and then return it. Forwarding *args and **kwargs matters for the same reason. A wrapper that takes fixed parameters breaks as soon as the function's signature changes.
Pitfall 3: lost metadata
Without functools.wraps, the decorated function reports the wrapper's name and docstring. This breaks logs, documentation tools, and anything that looks a function up by name.
| Symptom | Likely cause | Fix |
|---|---|---|
| `__name__` is `wrapper` | `functools.wraps` missing | Add `@functools.wraps(func)` to the wrapper |
| Calling the function returns a function | Factory used without parentheses | Write `@repeat(times=3)` |
| Calling returns `None` | Wrapper does not return | `return func(*args, **kwargs)` |
| `TypeError` about a missing argument on a method | Class-based decorator on a method | Use a function decorator, or implement `__get__` |
| Effects happen in the wrong order | Stacked decorators read backwards | Remember that the bottom decorator applies first |
Pitfall 4: class-based decorators on methods
An instance of CountCalls is not a function, so Python does not bind self when you access it through an object. Decorating a method with it fails with a missing-argument error. Function-based decorators avoid this problem, because plain functions bind automatically. Prefer them for methods.
Pitfall 5: stacked decorator order
The decorator closest to def applies first, and the top one wraps the result. At call time, the outermost wrapper runs first. When a caching or access-check decorator is stacked with others, the order decides what is cached or checked.
Debugging toolkit
functools.wraps stores the original function as __wrapped__. You can use it to test the original without the extra behavior.
import functools
import inspect
def logged(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logged
def add(a, b):
"""Add two numbers."""
return a + b
print(add.__name__) # add
print(add.__wrapped__(2, 3)) # 5, with no "calling" message
print(inspect.unwrap(add) is add.__wrapped__) # True
print(inspect.signature(add)) # (a, b)inspect.unwrap follows the __wrapped__ chain through every stacked layer. When a decorated function misbehaves, work through these steps.
Adding a print inside the wrapper, or stepping through it in a debugger, also shows quickly which layer runs and in what order.
Exercise
A teammate writes @retry above a function, but retry is defined as def retry(attempts): and returns a decorator. The function now seems to do nothing when called. What went wrong, and how do you fix it?
Show answer
@retry passes the function to retry as attempts, so the name is now bound to the inner decorator, not to a retrying wrapper. Calling it with the real arguments returns another function instead of running the original code. Write @retry(attempts=3) so the factory runs first and returns the decorator.