functools
- Python course
- Advanced
- Lesson 3/83
- 5 min
Learn caching with functools.lru_cache.
functools and lru_cache
The functools module provides helpers for higher-order functions. The most common is lru_cache, which keeps results of repeated calls in memory (memoization).
For example, recursive fib(n) is expensive; each call makes two sub-calls. Decorating it with @lru_cache(maxsize=None) stores results in a dict; if the same n shows up again it returns instantly.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)maxsize=None means an unlimited cache; a small maxsize evicts the least recently used entries (LRU).
Cache behavior and limits
lru_cache behaves like a dict: the key is the arguments passed to the function. If the same arguments come back, no computation happens.
Keeping maxsize small controls memory use. With maxsize=128, only the last 128 distinct calls are kept; a new call evicts the oldest. fib.cache_info() shows how many hits and misses occurred.
Note: arguments to a cached function must be hashable. You cannot pass a list or dict; use an immutable tuple instead.
Practice Cache fib with lru_cache
Decorate the recursive fib(n) with @lru_cache(maxsize=None). The base case n < 2 returns n; otherwise it returns fib(n-1) + fib(n-2). End with print(fib(10)).
Starter code
from functools import lru_cache
# fib recursive; decorate with lru_cache(maxsize=None)
# base: when n<2 return n
# otherwise return the sum of two sub-calls
# finally print the result of fib(10)Sample solution
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(10))Expected output
55
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the lru_cache concepts
| Term | Meaning |
|---|---|
lru_cache |
Result cache |
maxsize=None |
Unlimited cache |
maxsize=128 |
LRU eviction |
fib(n-1)+fib(n-2) |
Recursive step |
2 Add the lru_cache decorator
from functools import lru_cache
@____(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
Explanation: @lru_cache(maxsize=None) caches calls; fib speeds up.
3 Which argument type CANNOT be passed to an lru_cache function?
- Tuple
- Integer
- List Correct answer
- String
Explanation: A list is not hashable; it cannot be a cache key. Use a tuple instead.