Lesson 14 of 14 · 15 min

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

  1. count_calls(func): a decorator whose wrapper counts calls in wrapper.calls.
  2. memoize(func): a decorator that caches results in a dictionary keyed by the arguments.
  3. Decorate fib with @memoize so fib(200) returns instantly.
main.py
def count_calls(func):
    pass


def memoize(func):
    pass


def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)


print(fib(25))

Python 3.14 runs right here in your browser. The first run downloads about 10 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…