What does a decorator do, and why use functools.wraps?
Question
This decorator logs every call. Predict the four lines the code prints.
Then fix log_calls so that add keeps its own name and docstring. The wrapper should still log and return the result as before.
def log_calls(func): def wrapper(*args, **kwargs): print(f"calling {func.__name__}") return func(*args, **kwargs) return wrapper @log_calls def add(a, b): """Return the sum of a and b.""" return a + b print(add(2, 3)) print(add.__name__) print(add.__doc__)
Show hints (3)
- "WHAT @ MEANS"
@log_callsabovedef addis short foradd = log_calls(add). So which function does the nameaddpoint to after that line? - "WHOSE NAME IS IT"
addnow points to the innerwrapperfunction. Soadd.__name__is'wrapper', andadd.__doc__isNone, becausewrapperhas no docstring. - "THE STANDARD FIX"
Put
@functools.wraps(func)on the line abovedef wrapper. It copies the name, the docstring and a few other attributes fromfunconto the wrapper.
Show checked explanation
A decorator takes a function and returns a replacement, usually a wrapper that runs extra code before or after each call. @log_calls is short for add = log_calls(add). Without functools.wraps, add reports the wrapper's name and docstring, so help(), logs and other tools show the wrong 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 add(a, b): """Return the sum of a and b.""" return a + b print(add(2, 3)) print(add.__name__) print(add.__doc__)
calling add 5 add Return the sum of a and b.
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Without the fix, the code prints calling add, 5, wrapper and None.
@log_calls is shorthand. Right after Python creates add, it runs this once:
add = log_calls(add)log_calls returns wrapper, so the name add now points to wrapper. The original function is kept inside the wrapper as func. A call to add(2, 3) runs wrapper(2, 3). It prints calling add, calls func(2, 3) and returns 5.
The log line says add because the wrapper reads func.__name__. But add itself is now the wrapper, so its attributes describe the wrapper:
| what you read | without wraps | with wraps |
|---|---|---|
add.__name__ | wrapper | add |
add.__doc__ | None | Return the sum of a and b. |
add.__wrapped__ | no such attribute | the original add |
inspect.signature(add) | (*args, **kwargs) | (a, b) |
So every tool that reads these attributes shows the wrong thing: help(add), logs that print function names, test reports, and frameworks that register handlers by name. Decorate ten functions without wraps, and all ten are called wrapper.
functools.wraps(func) is itself a decorator. It copies __name__, __qualname__, __doc__, __module__ and a few other attributes from func onto the wrapper. It also saves the original function as __wrapped__, so a test can call it without the wrapper. inspect.signature follows that link, which is why it shows (a, b). wraps does not change what the wrapper does.
Common mistakes
- Calling
func(*args, **kwargs)in the wrapper withoutreturn. The function still runs, but every decorated function now returnsNone. - Giving the wrapper fixed parameters, like
def wrapper(a, b). It then breaks on functions with other parameters: after decoratingsquare(x), the callsquare(3)raisesTypeError. - Forgetting
return wrapperat the end of the decorator. The nameaddthen holdsNone, and the first call fails with'NoneType' object is not callable.
Follow-up questions
- "How would you write a decorator with arguments, like
@retry(times=3)?"@retry(times=3)first callsretry(times=3), and that call must return the real decorator. So you nest three functions:retry(times)returnsdecorator(func), which returnswrapper(*args, **kwargs).@functools.wraps(func)still goes onwrapper. - "When does the decorator's own code run?"
log_calls(add)runs once, when Python executes thedef, usually at import time. Only the wrapper runs on every call. So aprintplaced inlog_calls, outsidewrapper, appears once, even ifaddis never called. - "Two decorators are stacked. In what order do they apply?" From the bottom up:
@aabove@babovedef fmeansf = a(b(f)). Calls go the other way. The wrapper fromaruns first and calls the wrapper fromb, which callsf.
What a strong answer covers
Explains @ as a plain reassignment and writes a wrapper with *args, **kwargs that returns the result. Adds functools.wraps without being asked, says what breaks without it, and knows the decorator runs once, at definition time.
Open in interactive practice deck →