Sub topic 5
Fixing it with wraps
This chapter assumes you can write a simple decorator with an inner wrapper function and *args, **kwargs. The previous chapter showed that such a decorator replaces the original function with the wrapper, and the original's name and docstring are lost. Here you fix that with functools.wraps.
What wraps does
functools.wraps is a decorator that you apply to the inner wrapper. You give it the function being wrapped, and it copies the original's identifying information onto the wrapper. The copied attributes are __module__, __name__, __qualname__, __doc__, and __annotations__. It also merges the original's __dict__ into the wrapper's. Finally, it sets __wrapped__ on the wrapper, which points back to the original function.
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def greet(name):
"""Return a greeting."""
return f"Hello, {name}"
print(greet("Ada"))
print(greet.__name__) # greet
print(greet.__doc__) # Return a greeting.
print(greet.__wrapped__ is not None) # TrueCalling greet("Ada") prints calling greet and then Hello, Ada. The other three lines show that greet still reports its own name and docstring, even though the object bound to that name is now wrapper.
Comparing a naive and a careful decorator
The difference also shows up in tools that inspect functions. inspect.signature follows __wrapped__, so it reports the original parameters instead of (*args, **kwargs).
import functools
import inspect
def naive(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def careful(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@naive
def add(a, b=1):
"""Add two numbers."""
return a + b
@careful
def mul(a, b=1):
"""Multiply two numbers."""
return a * b
print(add.__name__, add.__doc__) # wrapper None
print(mul.__name__, mul.__doc__) # mul Multiply two numbers.
print(inspect.signature(add)) # (*args, **kwargs)
print(inspect.signature(mul)) # (a, b=1)This matters in practice for several reasons:
help()and documentation generators show the real docstring.- Tracebacks and log messages name the real function.
- Frameworks that register functions by
__name__, such as test runners and web routers, don't see every function aswrapper. - Editors and type checkers can still read the signature.
Using wraps in a decorator with arguments
When a decorator takes its own arguments, there is one more level of nesting. Put wraps on the innermost function, the one that replaces the decorated function.
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(times=2)
def ping():
"""Print a ping."""
print("ping")
ping()
print(ping.__name__) # pingCommon errors
- Forgetting the argument.
@functools.wrapswithout(func)does not raise an error when the decorator is defined. It turnswrapperinto a partial object. The failure appears later, when you call the decorated function and it receives the wrong arguments. Always write@functools.wraps(func). - Putting
wrapson the wrong function. It belongs on the wrapper, not on the outer decorator function. - Assuming it changes behavior.
wrapsonly copies metadata. It does not make the wrapper accept different arguments or return different values. - Expecting a copy of mutable state. The wrapper's
__dict__is updated with the original's entries, so the two functions can end up sharing the same attribute values. Don't rely on them being independent.
The next chapter covers update_wrapper, the function that wraps calls internally, and looks at __wrapped__ in more detail.
Exercise
A teammate writes a timing decorator with an inner function called wrapper and forgets functools.wraps. After decorating load_data, load_data.__name__ prints wrapper and help(load_data) shows no docstring. What one-line change fixes both problems, and where does it go?
Show answer
Add @functools.wraps(func) on the line directly above def wrapper(...) inside the decorator, where func is the function the decorator receives. This copies __name__, __doc__, and the other metadata onto wrapper and sets __wrapped__. It does not change what the function does.
Exercise
Why does inspect.signature(mul) return (a, b=1) in the example above, even though the object bound to mul is the wrapper with a (*args, **kwargs) signature?
Show answer
wraps sets mul.__wrapped__ to the original function, and inspect.signature follows __wrapped__ to report the original function's parameters.