Python 3D Academyবাংলা

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:

  1. @announce, nearest the function, wraps first (the tissue paper)
  2. @shout wraps that (the box)
  3. 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 one def; 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:

  1. repeat(times) takes the setting and returns a decorator
  2. that decorator takes func and returns a wrapper
  3. the wrapper uses both times and func

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 million

Why 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 @shout and @announce changes the output; read them bottom-up for wrapping, top-down for running.
  • @repeat without the setting. @repeat (no brackets) passes your function in as times; write @repeat(3).
  • Caching with a list argument. @cache stores answers by argument, so arguments must be hashable: f([1]) gives TypeError: unhashable type: 'list'. Pass a tuple.
  • Caching a function with side effects. A cached function that prints only prints the first time.

Quiz

  1. 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())
  2. With @a above @b above def f, which wrapper does a call enter first?

    • a's wrapper (the outer layer)
    • b's wrapper
    • The real f
  3. 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())
  4. 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)
  5. 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

  1. Write a decorator with a setting, repeat(times), whose wrapper calls the function times times (passing any arguments through) and returns a list of the results.

  2. bold and italic are written for you. Put both on title(text), which returns text, so that title("Hi") gives "<b><i>Hi</i></b>".

  3. Write ways(n): the number of ways to climb n stairs taking 1 or 2 steps at a time (ways(0) and ways(1) are 1; otherwise ways(n - 1) + ways(n - 2)). Use @functools.cache, so each answer is worked out only once.