Sub topic 13
Decorators as Higher-Order Functions
This chapter assumes you know how to define functions with def, use *args and **kwargs, and have read the earlier chapters on closures and functions that return functions. A decorator combines these ideas.
A decorator is a function that takes and returns a function
A higher-order function takes a function as an argument, returns a function, or does both. A decorator does both. It receives a function, builds a new function that wraps it, and returns the new one. The wrapper can run code before or after the original, change its arguments, or change its result.
from functools import wraps
def log_calls(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def add(a, b):
return a + b
print(add(2, 3))
# calling add
# 5wrapper is a closure. It remembers func from the call to log_calls that created it, in the same way make_multiplier remembered factor.
What the @ syntax does
The @log_calls line above def add is shorthand for a reassignment after the function is defined:
def add(a, b):
return a + b
add = log_calls(add)The name add now refers to wrapper, not to the original function. The original survives only inside the closure. Python applies the decorator once, when the def statement runs. It does not apply it on each call.
Why wrapper takes *args and **kwargs
The decorator does not know in advance which function it will wrap. Writing wrapper(*args, **kwargs) and forwarding both to func lets one decorator work with any signature. Remember to return the result of func(...). If you leave out the return, the decorated function silently returns None.
Why @wraps matters
Without @wraps(func), the wrapper hides the identity of the original function. Its __name__ is "wrapper" and its docstring is lost. This confuses debuggers, logs, and documentation tools. functools.wraps copies the name, docstring, and other metadata from func onto wrapper.
from functools import wraps
def plain(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def careful(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@plain
def f():
"""Docs for f."""
@careful
def g():
"""Docs for g."""
print(f.__name__, f.__doc__) # wrapper None
print(g.__name__, g.__doc__) # g Docs for g.@wraps is itself a decorator that takes an argument. It is a function that returns a decorator.
Common errors
- Forgetting to return
wrapper. The decorated name becomesNone, and the next call fails withTypeError: 'NoneType' object is not callable. - Calling the function inside the decorator body. Write
return wrapper, notreturn wrapper(). The decorator must hand back a function, not the result of calling one. - Writing
@log_calls()for a decorator with no parameters. This callslog_callswith no arguments and raises aTypeError. Only decorators built to take arguments are written with parentheses.
Summary
A decorator is a higher-order function that takes a function and returns a replacement, usually a closure. @name is shorthand for f = name(f). Use *args and **kwargs so the wrapper accepts any call, return the wrapped result, and apply @wraps to keep the original metadata.
Exercise
Write a decorator twice that calls the decorated function two times with the same arguments and returns the result of the second call. What does add = twice(add) change about the name add?
Show answer
Define def twice(func): containing @wraps(func) and def wrapper(*args, **kwargs):. In wrapper, call func(*args, **kwargs) once and discard the result, then return func(*args, **kwargs). Finish with return wrapper. The assignment add = twice(add) rebinds the name add to wrapper, so every later call to add goes through the wrapper. The original function stays reachable only through the closure variable func.