Full answer
python
from functools import lru_cache, partial
calls = 0
@lru_cache(maxsize=None)
def fib(n):
global calls
calls += 1
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80), calls, fib.cache_info())
try:
lru_cache()(lambda xs: sum(xs))([1, 2])
except TypeError as e:
print("TypeError:", e)
def price_with_tax(amount, rate):
return round(amount * (1 + rate), 2)
gst18 = partial(price_with_tax, rate=0.18)
print(gst18(100), gst18.func.__name__, gst18.keywords)Output:
text
23416728348467685 81 CacheInfo(hits=78, misses=81, maxsize=None, currsize=81)
TypeError: unhashable type: 'list'
118.0 price_with_tax {'rate': 0.18}Without caching, fib(80) would make billions of calls; with it, each value from 0 to 80 is computed once, so calls is 81. cache_info() shows hits and misses. A list argument fails because cache keys must be hashable. Cached functions keep results alive for the life of the process, so bound the size for open-ended inputs and avoid caching methods on instances without care, since self becomes part of the key and keeps objects alive. partial builds a one-argument GST calculator from a general function.
python
from functools import lru_cache, partial
calls = 0
@lru_cache(maxsize=None)
def fib(n):
global calls
calls += 1
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80), calls, fib.cache_info())
try:
lru_cache()(lambda xs: sum(xs))([1, 2])
except TypeError as e:
print("TypeError:", e)
def price_with_tax(amount, rate):
return round(amount * (1 + rate), 2)
gst18 = partial(price_with_tax, rate=0.18)
print(gst18(100), gst18.func.__name__, gst18.keywords)Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- lru_cache memoises by arguments
- cache is unbounded
- Arguments must be hashable
- Cached values live for the process
- partial fixes arguments
Common mistakes
- Caching functions with side effects
- Unbounded caches on unbounded inputs
Follow-ups
- How would you cache with expiry?
- Why can lru_cache on methods leak memory?
Tips
- Show cache_info