Sub topic 6
Keeping name and docstring with functools.wraps
This chapter assumes you can write a basic decorator: a function that takes a function and returns a wrapper. You should also know *args and **kwargs forwarding and the @ syntax. Here you will see what a plain wrapper breaks and how functools.wraps fixes it.
The problem: the wrapper replaces the original
A decorator returns a new function, and that function takes over the original's name. The new function has its own __name__ and __doc__, so the original's identity is lost.
def shout(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs).upper()
return wrapper
@shout
def greet(name):
"""Return a greeting for name."""
return f"hello, {name}"
print(greet.__name__) # wrapper
print(greet.__doc__) # None
help(greet) # describes wrapper, not greetThe call still works. The metadata is wrong, though, and that causes real trouble:
- Tracebacks and logs show
wrapperinstead of the real function name. help()and documentation tools show no docstring.- Frameworks that register functions by
__name__can end up with every function under the same key. - Debugging gets harder because every decorated function looks the same.
The fix: functools.wraps
functools.wraps is a decorator that you apply to the wrapper. It copies metadata from the original function onto the wrapper.
import functools
def shout(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs).upper()
return wrapper
@shout
def greet(name):
"""Return a greeting for name."""
return f"hello, {name}"
print(greet.__name__) # greet
print(greet.__doc__) # Return a greeting for name.
print(greet("Ana")) # HELLO, ANANote that @functools.wraps(func) takes an argument, so it is itself a decorator factory. You will build your own in a later chapter.
What wraps copies
functools.wraps calls functools.update_wrapper, which does the following:
| Attribute | What happens |
|---|---|
| `__module__` | Copied |
| `__name__` | Copied |
| `__qualname__` | Copied |
| `__doc__` | Copied |
| `__dict__` | Updated with the original's attributes |
| `__wrapped__` | Set to the original function |
Python 3.12 and later also copy __type_params__, and the standard library may add further attributes in newer versions.
Reaching the original with `__wrapped__`
functools.wraps also sets wrapper.__wrapped__ to the original function. This lets you bypass the decoration, which is useful in tests. It also lets inspect.signature report the original signature instead of (*args, **kwargs).
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=10):
"""Add two numbers."""
return a + b
print(inspect.signature(add)) # (a, b=10)
print(add.__wrapped__(1, 2)) # 3, with no "calling" messageWhere to put it
Apply functools.wraps to the innermost wrapper, the function that the decorator returns. It takes the original function as its argument.
import functools
import time
def timer(func):
@functools.wraps(func) # on the wrapper, passing 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 wrapperThe finally block prints the timing even if the function raises an exception.
Common mistakes
- Forgetting it. Nothing fails, so the problem shows up later as confusing logs or broken registries. Make
@functools.wraps(func)part of your decorator template. - Writing
@functools.wrapswithout(func). This passes the wrapper as the thing to copy from and produces a broken result. Always call it with the original function. - Putting it on the outer function. It belongs on the inner wrapper, not on the decorator itself.
Exercises
Exercise
A decorator defines def wrapper(*args, **kwargs) without functools.wraps. After decorating a function called load_data, what does load_data.__name__ return, and which one-line change fixes it?
Show answer
It returns "wrapper". Add @functools.wraps(func) directly above def wrapper(...), after importing functools.
Exercise
A function compute was decorated with a decorator that uses functools.wraps. How can you call the original, undecorated function in a test?
Show answer
Call compute.__wrapped__(...). The wraps decorator stores the original function in the __wrapped__ attribute of the wrapper.