Sub topic 7
Why cache function results
This chapter assumes you can write Python functions, read a basic decorator, and know that a dict key must be hashable. It explains the idea behind functools.cache before you meet the decorator itself.
The cost of repeated work
A function that is called twice with the same arguments often does the same work twice. For a slow function, such as a heavy calculation or a recursive search, that waste adds up quickly.
Memoization is the technique of storing a function's result the first time it is computed, keyed by the arguments, and returning the stored result on later calls with the same arguments. The name comes from "memo": the function writes itself a note.
The classic example is a recursive Fibonacci function. This version counts how often it is called.
calls = 0
def fib(n):
global calls
calls += 1
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(25)) # 75025
print(calls) # 242785Computing one number takes 242,785 calls. The reason is that fib(n - 1) and fib(n - 2) both end up calling fib(n - 3), and the overlap repeats at every level. The number of calls grows exponentially with n, while the number of distinct values needed is only n + 1.
Memoizing by hand
You can remove the repeated work with a dictionary that maps arguments to results.
memo = {}
computed = 0
def fib_memo(n):
global computed
if n in memo:
return memo[n]
computed += 1
result = n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)
memo[n] = result
return result
print(fib_memo(25)) # 75025
print(computed) # 26The body now runs once for each value from 0 to 25, which is 26 times, instead of 242,785 times. Every other call is a dictionary lookup.
The control flow is the same every time:
What makes a function safe to memoize
Memoization trades memory for time, and it is only correct under certain conditions.
- The function is pure. The same arguments must always produce the same result, and the function must not depend on hidden state such as the clock, a file, a database row, or a global variable that changes.
- Skipping the call must not matter. If the function prints, writes a file, or sends a request, a cached call skips that side effect.
- The arguments must be hashable, because they become a dictionary key.
- The set of distinct arguments must be bounded, or you must be willing to bound the cache. Every new argument combination adds an entry.
The next example breaks the first rule. A cached version would return the first time forever.
import time
def current_hour_label():
return time.strftime("%H:00")A memoized current_hour_label() would keep returning the label from the first call, even after the hour changed. Nothing warns you, because the cache simply returns what it stored.
When caching pays off
Caching helps most when these conditions hold:
- The function is expensive relative to a dictionary lookup.
- The same arguments recur often, as in recursion with overlapping subproblems, repeated parsing of the same strings, or lookups against fixed data.
- Results are small enough to keep in memory.
If every call has different arguments, the cache never gets a hit. It only uses memory and adds the cost of building keys. Measure the hit rate before assuming a cache helps. The cache_info() method, covered in a later chapter, reports it.
Why use functools instead of a dict
The hand-written version works, but it has drawbacks. It mixes caching logic into the function body, uses a global dictionary, has no size limit, and needs repeating for every function you want to cache. Because the logic is separate from the calculation, it is a natural fit for a decorator. The functools module provides cache and lru_cache for exactly this, and the next chapters show how they work.
Exercise
A function get_price(product_id) reads the current price from a database that is updated every few minutes. A teammate wants to memoize it to speed up the checkout page. Name the rule it breaks and describe what would go wrong.
Show answer
It is not pure, because the same product_id can return different results as the database changes. A memoized version would return the price from the first call indefinitely, so customers would see stale prices and no error would signal the problem.