Sub topic 14
Common pitfalls and how to debug them
Most decorator bugs come from a few causes: a missing call, a wrapper that drops something, or a wrapper that doesn't match the kind of function it wraps. This chapter lists those mistakes, shows how each one looks, and gives you tools to find them quickly.
It assumes you can write a decorator with functools.wraps, use the @ syntax, build a decorator factory, and read basic async def code. The earlier chapters cover all of these.
Pitfall 1: forgetting to call a decorator factory
A decorator factory such as repeat(times) returns the real decorator. Writing @repeat without parentheses passes the decorated function as times. Nothing fails at definition time.
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 # bug: should be @repeat(times=3)
def say(message):
print(message)
print(say) # <function repeat.<locals>.decorator at 0x...>
result = say("hello") # prints nothing
print(result) # <function say at 0x...>say is now the inner decorator function. Calling say("hello") passes the string "hello" as func, so you get back a wrapper and nothing prints. The error shows up far from its cause.
The <locals>.decorator in the printed name is the clue. A cheap defense is to validate the argument when the factory is called:
def repeat(times):
if not isinstance(times, int):
raise TypeError("repeat() needs an int, use @repeat(times=3)")
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 decoratorWith this guard, @repeat fails at import time with a message that names the fix.
Supporting both forms on purpose
Sometimes you want both @retry and @retry(attempts=5) to work. Make the function an optional first parameter and the options keyword-only:
import functools
def retry(func=None, *, attempts=3):
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
last_error = None
for _ in range(attempts):
try:
return f(*args, **kwargs)
except Exception as exc:
last_error = exc
raise last_error
return wrapper
if func is not None: # used as @retry
return decorator(func)
return decorator # used as @retry(attempts=5)
@retry
def a():
return "a"
@retry(attempts=5)
def b():
return "b"
print(a(), b()) # a bThe keyword-only * matters. It stops @retry(5) from being read as "the function is 5".
Pitfall 2: losing metadata
A wrapper without functools.wraps replaces the original's name, docstring, and signature.
import inspect
def noisy(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@noisy
def add(a, b):
"""Add two numbers."""
return a + b
print(add.__name__) # wrapper
print(add.__doc__) # None
print(inspect.signature(add)) # (*args, **kwargs)This breaks several things:
- Tracebacks and logs show
wrapperfor every decorated function. help()and documentation generators lose the docstring.- Frameworks that read names or signatures behave wrongly. Examples are routing tables, dependency injection, and test collectors.
Adding @functools.wraps(func) to the wrapper fixes the name and docstring. It also sets add.__wrapped__ to the original, and inspect.signature follows that link, so the real signature (a, b) is reported again.
Pitfall 3: wrappers that drop arguments or results
Three small mistakes cause most silent breakage:
- The wrapper accepts only specific parameters, so a call with different arguments raises
TypeError. Use*args, **kwargs. - The wrapper calls
func(...)but forgetsreturn. The decorated function now always returnsNone. - The wrapper swallows exceptions with a bare
except. Callers can no longer tell failure from success.
If a decorated function suddenly returns None, check for a missing return in the wrapper first.
Pitfall 4: stacking order surprises
Decorators apply from the bottom up, but the wrappers run from the top down. The outermost decorator sees the call first.
import functools
def tag(label):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("enter", label)
return func(*args, **kwargs)
return wrapper
return decorator
@tag("outer")
@tag("inner")
def run():
print("body")
run()
# enter outer
# enter inner
# bodyOrder has real consequences. Suppose a caching decorator sits above an authentication check. The cache can then return a result to a caller who never passed the check. Likewise, a registration decorator that stores the function (a route table, for example) should usually be outermost. Otherwise it registers the undecorated function and bypasses the behavior you stacked on.
Pitfall 5: class-based decorators on methods
An instance of a class with __call__ is callable, but it is not a function. Functions bind self automatically when accessed through an instance. Plain instances don't, so the instance is never passed to the method.
import functools
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)
class Greeter:
name = "Ada"
@CountCalls
def hello(self):
return f"hi {self.name}"
Greeter().hello()
# TypeError: ... missing 1 required positional argument: 'self'The fix is to implement __get__, which makes the decorator a descriptor. It then binds the instance the way a function does:
import functools
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:
return self
return functools.partial(self, instance)
class Greeter:
name = "Ada"
@CountCalls
def hello(self):
return f"hi {self.name}"
g = Greeter()
print(g.hello()) # hi Ada
print(Greeter.hello.calls) # 1The counter lives on the decorator object, so all Greeter instances share it. If you want one decorator to work on both functions and methods, a function-based decorator is simpler.
Pitfall 6: wrapping async functions with a sync wrapper
A normal wrapper around an async def function calls it and gets a coroutine object back. It returns that object without running it. Anything the wrapper does "around" the call happens before the coroutine does any work.
import asyncio
import functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs) # only creates the coroutine
print(f"{time.perf_counter() - start:.3f}s")
return result
return wrapper
@timer
async def work():
await asyncio.sleep(0.2)
return "done"
print(asyncio.run(work()))
# 0.000s <- measured nothing
# doneThe fix is an async def wrapper that awaits the call. If one decorator must support both kinds of function, check inspect.iscoroutinefunction(func) and return the matching wrapper.
Pitfall 7: caching and shared state
functools.lru_cacherequires hashable arguments. Passing a list raisesTypeError: unhashable type.- Applied to a method,
lru_cacheincludesselfin the cache key. The cache then keeps every instance alive until you clear it or it evicts the entry. - State kept in a decorator, such as a counter or a cache dict, is created once at decoration time and shared by every call. This is what you want for a global counter. It is a bug if you expected per-instance or per-test state.
Pitfall 8: confusing definition time with call time
The code in the outer decorator and the factory runs once, when the module is imported. Only the wrapper body runs on each call. Registration, validation of decorator arguments, and print statements placed in the decorator body therefore fire at import. Expensive work there slows every import of the module. Work that depends on runtime state belongs inside the wrapper.
Debugging toolkit
The table maps common symptoms to causes and first checks.
| Symptom | Likely cause | First check |
|---|---|---|
| Function is named `decorator` or `wrapper` | Missing call on a factory, or missing `wraps` | `print(func)` and `func.__name__` |
| Decorated function returns `None` | Wrapper doesn't `return` | Read the wrapper body |
| `TypeError` about arguments | Wrapper has a fixed signature | Switch to `*args, **kwargs` |
| `missing ... 'self'` | Class-based decorator on a method | Add `__get__` or use a function |
| Timing near zero on async code | Sync wrapper around a coroutine function | Make the wrapper `async def` |
| Auth or cache bypassed | Wrong stacking order | Print the call order |
Two standard tools help once wraps is in place:
import functools
import inspect
def logged(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@logged
@logged
def add(a, b):
return a + b
print(add.__wrapped__) # the inner wrapper, one layer down
print(inspect.unwrap(add)) # <function add at 0x...>, the original
print(inspect.signature(add)) # (a, b)__wrapped__ removes one layer, and inspect.unwrap removes all of them. The unwrapped function is also what you call in a unit test when you want to test the logic without the decorator's behavior.
A short checklist
Before you ship a decorator, confirm each of these:
- The wrapper accepts
*args, **kwargsand returns the wrapped function's result. - The wrapper has
@functools.wraps(func). - Factories are applied with parentheses, or the decorator handles both forms deliberately.
- Async functions get an async wrapper.
- Class-based decorators used on methods define
__get__. - You have thought about stacking order and about what runs at import.
Exercise
This code prints nothing and greet("Ana") returns a function instead of a string. Name the mistake and write the corrected decorator line.
def twice(times):
def decorator(func):
def wrapper(args, kwargs):
return [func(args, **kwargs) for _ in range(times)]
return wrapper
return decorator
@twice
def greet(name):
return "hi " + name
Show answer
twice is a decorator factory, but it is applied without parentheses. @twice calls twice(greet), so times is the function greet and the name greet is bound to the inner decorator. Calling greet("Ana") then passes "Ana" as func and returns a wrapper function. The fix is @twice(times=2) above greet. Adding @functools.wraps(func) to the wrapper is also good practice.
Exercise
A coroutine function load() is decorated with a timing decorator whose wrapper is a plain def. The timer always prints about 0.000s even though load() sleeps for a second. Why does this happen, and how do you fix it?
Show answer
The plain wrapper calls load(), which only creates a coroutine object and runs none of its body. The timer stops before the coroutine is awaited, so it measures almost nothing. Rewrite the wrapper as async def and use result = await func(*args, **kwargs) between the two timer readings, keeping @functools.wraps(func) on it.