Stacking decorators, settings and caching
🌍 In real life. A shop wraps a gift in tissue paper, then puts it in a box, then ties a ribbon round the box. To open it, you meet the layers the other way round: ribbon first, box next, tissue last, and finally the gift.
Decorators stack the same way. With @shout above @announce above def greet:
@announce, nearest the function, wraps first (the tissue paper)@shoutwraps that (the box)- a call goes in through shout's wrapper, then announce's, reaches the real
greet, then comes back out the other way
The idea in one sentence: stacked decorators wrap from the bottom up and run from the top down, a decorator with settings needs one more layer, and @functools.cache remembers a function's answers.
Its words:
- stacking: several
@lines above onedef; the one nearest the function wraps first - decorator factory:
repeat(3)takes a setting and returns a decorator - cache: remembered answers, looked up instead of worked out again
Decorators with settings. Sometimes you want @repeat(3): a decorator that takes a setting. That needs one more layer, step by step:
repeat(times)takes the setting and returns a decorator- that decorator takes
funcand returns a wrapper - the wrapper uses both
timesandfunc
It looks like a lot of defs, but each layer has just one job.
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
results = []
for _ in range(times):
results.append(func(*args, **kwargs))
return results
return wrapper
return decorator
@repeat(3)
def cheer(team):
return "Go " + team + "!"
print(cheer("Tigers"))A ready-made decorator: caching. A shopkeeper who has added up the same bill before just remembers the total. @functools.cache gives a function that kind of memory: the first time it sees some arguments it works out the answer, and after that it hands back the remembered answer straight away. It turns the slow recursive Fibonacci from Chapter 17 into a fast one:
import functools
calls = 0
@functools.cache
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(30))
print("worked out", calls, "times") # without the cache: over a millionWhy cache? It's the memo from Lesson 17.4, written for you: a recursive fib that made 21,891 calls for fib(20) makes about 21 with @cache, because each answer is worked out once. The price is memory for every remembered answer.
Mistakes and edge cases.
- The order of stacked decorators. Swapping
@shoutand@announcechanges the output; read them bottom-up for wrapping, top-down for running. - @repeat without the setting.
@repeat(no brackets) passes your function in astimes; write@repeat(3). - Caching with a list argument.
@cachestores answers by argument, so arguments must be hashable:f([1])givesTypeError: unhashable type: 'list'. Pass a tuple. - Caching a function with side effects. A cached function that prints only prints the first time.
Quiz
What does this print?
def add_a(func): def wrapper(): return func() + "a" return wrapper def add_b(func): def wrapper(): return func() + "b" return wrapper @add_a @add_b def word(): return "x" print(word())With
@aabove@babovedef f, which wrapper does a call enter first?- a's wrapper (the outer layer)
- b's wrapper
- The real f
What does this print?
def repeat(times): def decorator(func): def wrapper(): return [func() for _ in range(times)] return wrapper return decorator @repeat(2) def hi(): return "hi" print(hi())What does this print?
import functools count = 0 @functools.cache def slow_square(n): global count count += 1 return n * n print(slow_square(4), slow_square(4), slow_square(5), count)Which line has a mistake?
def repeat(times): def decorator(func): def wrapper(): return [func() for _ in range(times)] return wrapper return decorator @repeat def hi(): return "hi" print(hi())
Coding tasks
Write a decorator with a setting,
repeat(times), whose wrapper calls the functiontimestimes (passing any arguments through) and returns a list of the results.boldanditalicare written for you. Put both ontitle(text), which returnstext, so thattitle("Hi")gives"<b><i>Hi</i></b>".Write
ways(n): the number of ways to climbnstairs taking 1 or 2 steps at a time (ways(0)andways(1)are 1; otherwiseways(n - 1) + ways(n - 2)). Use@functools.cache, so each answer is worked out only once.