Wrappers that fit any function
🌍 In real life. A travel adapter has holes that fit any plug, and passes the electricity straight through to whatever you plug in. It doesn't care whether it's a phone charger or a hair dryer.
The wrappers in the last lesson only fitted functions with exactly one argument. A wrapper written with *args and **kwargs (Chapter 15) is like that adapter:
def wrapper(*args, **kwargs):accepts any argumentsfunc(*args, **kwargs)passes them straight through to the real function- so one decorator now fits every function, whatever its parameters
The idea in one sentence: a wrapper written as def wrapper(*args, **kwargs): accepts any arguments and passes them straight on with func(*args, **kwargs), so one decorator fits every function.
Its words:
*args, **kwargs: collect any positional and keyword arguments (Chapter 15)- pass-through:
func(*args, **kwargs)spreads them back out for the original - function attribute: a value stored on the wrapper itself, like
wrapper.calls
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(func.__name__, "called with", args, kwargs)
return func(*args, **kwargs)
return wrapper
@log
def add(a, b):
return a + b
@log
def greet(name, polite=False):
return ("Good day, " if polite else "Hi, ") + name
print(add(2, 3))
print(greet("Ana", polite=True))
print(add.__name__)A wrapper can remember things, step by step. A shop counter clicks once for every customer. A decorator can count calls the same way:
- the wrapper is a function, and functions can carry attributes, like
wrapper.calls = 0 - each time it runs, the wrapper adds one:
wrapper.calls += 1 - after a few calls,
greet.callstells you how many there were
def counted(func):
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@counted
def serve(customer):
return "served " + customer
serve("Ana")
serve("Bo")
serve("Cy")
print(serve.calls)Mistakes and edge cases.
- A wrapper with fixed parameters.
def w():aroundadd(a, b)givesTypeError: d.<locals>.w() takes 0 positional arguments but 2 were given. - Forgetting the stars when passing on.
func(args, kwargs)passes a tuple and a dict as two arguments; it must befunc(*args, **kwargs). - Losing the function's name. The decorated function's
__name__becomeswrapper;@functools.wraps(func)above the wrapper keeps the original name and docstring. - Counting on the wrong object. Store the count on the wrapper (
wrapper.calls), which is what the decorated name now points to.
Quiz
What does this print?
def passthrough(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @passthrough def area(w, h=1): return w * h print(area(3, h=4), area(5))Why write the wrapper as
def wrapper(*args, **kwargs)?- So the decorator fits functions with any arguments
- To make the function run faster
- Because wrappers can't have named parameters
What does this print?
def counted(func): def wrapper(*args): wrapper.calls += 1 return func(*args) wrapper.calls = 0 return wrapper @counted def ping(): return "pong" for _ in range(4): ping() print(ping.calls)What does this print?
import functools def plain(func): def wrapper(*args): return func(*args) return wrapper def neat(func): @functools.wraps(func) def wrapper(*args): return func(*args) return wrapper @plain def one(): return 1 @neat def two(): return 2 print(one.__name__, two.__name__)Which line has a mistake? (log should work on any function.)
def log(func): def wrapper(): print("calling") return func() return wrapper @log def add(a, b): return a + b print(add(2, 3))
Coding tasks
Write a decorator
passthroughwhose wrapper accepts any arguments and keywords, passes them to the function, and returns its result.Write a decorator
countedthat keeps a count of how many times the function has been called, in an attributecallson the wrapper (starting at 0).Write a decorator
keep_namethat passes any arguments through and usesfunctools.wraps, so the decorated function keeps its own__name__.