Decorators and memoization
In Python, functions are objects: you can pass them to other functions and return them. A decorator is a function that takes a function and returns a new, improved one:
def shout(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@shout
def greet(name):
return f"hello, {name}"
print(greet("tino")) # HELLO, TINO
@shout above the def is shorthand for greet = shout(greet). The wrapper stands in for the original, can do things before and after it, and calls it in between.
*args, **kwargs means "accept any arguments", so the wrapper works for any function. The wrapper is a closure: it remembers func.
Memoization
Recursive functions often redo the same work. The direct Fibonacci function:
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
works out fib(30) with over a million calls. A memoizing decorator remembers each answer the first time and looks it up afterwards, so each value is computed once. Python ships one as functools.cache; in this lesson you write your own.
Functions are objects, so you can attach data to them: wrapper.calls = 0.
Your task
count_calls(func): a decorator whose wrapper counts calls inwrapper.calls.memoize(func): a decorator that caches results in a dictionary keyed by the arguments.- Decorate
fibwith@memoizesofib(200)returns instantly.