functools is a standard-library module with helpers for adapting, composing and reusing functions.
Bind some inputs in advance, preserve function metadata and reuse cached results while understanding argument keys, eviction and freshness.
Repeated requests can reuse an earlier answer, but only when that answer is
still valid and safe to share. Start with a dictionary captured by a wrapper,
then examine lru_cache through its hit, miss, and eviction behaviour.
partial and reduce extend the same idea of treating functions as values:
configure a call, or combine a sequence of transformations.

Cache a slow host-to-region lookup
Resolving a host to a region means asking a slow directory — worth remembering once two million log rows only mention thirty distinct hosts:
The key is args, the tuple of arguments — it works because a tuple of strings
is hashable. Hold on to that; it comes back below.
Preparing this topic’s interactive investigation…
Bound the region cache with lru_cache
lru_cache is a decorator factory — the last lesson's shape — where maxsize
is the setting. Over the hand-written version it adds a bound (past
maxsize, the least recently used entry is evicted to make room, the "LRU"),
statistics (cache_info()), and control (cache_clear()).
from functools import lru_cache
@lru_cache(maxsize=None)
def region_of(host):
return host[:2]
for host in ["eu-1", "ap-1", "eu-1", "eu-2", "eu-1", "ap-1"]:
region_of(host)
info = region_of.cache_info()
print(info.hits, info.misses)A cache smaller than the set of keys cycling through it can be worse than no cache at all:
from functools import lru_cache
calls = []
@lru_cache(maxsize=2)
def lookup(key):
calls.append(key)
return key
for key in ["a", "b", "c", "a", "b"]:
lookup(key)
print(len(calls))Watching a bounded cache fill and evict
With maxsize=2, only two answers fit. Step through the calls and watch which
key gets thrown out. It's the one used longest ago, not the one added
earliest:
Here's the decision the wrapper makes on each call:
That thrashing example above is exactly what this diagram predicts: each key arrives right after its own entry was evicted, so every call takes the miss branch.
Cache a tax total safely
The cache key has to be hashable, because it's a dict key:
TypeErrorRun it and read the error. Change the call so the argument can be used as a cache key.
The more serious rule is about meaning: a cache is only correct when the result depends on nothing but the arguments.
from functools import lru_cache
rate = 10
@lru_cache(maxsize=None)
def with_tax(price):
return price + price * rate // 100
first = with_tax(200)
rate = 20
print(first, with_tax(200))Before reaching for @lru_cache, check: the function is pure (no global,
file, clock or database read), its arguments are hashable, the result is
safe to share (a cached list is the same list handed to every caller — one
mutating it affects the rest), and memory is bounded — set a real maxsize
unless the key space is small and known.
A cache reuses the returned object too
Hashable arguments are only the entry condition. The cached result is an object with the same aliasing rules as any other object, and a hit returns that stored object rather than rerunning the function to build a fresh one.
The mutation is visible on the hit. For a schema shared by readers, returning a tuple communicates an immutable sequence. If each caller needs a mutable list, cache an immutable representation and make a list at the boundary. A deep copy on every hit is another cost to evaluate, not free cache speed.
The cache also holds strong references to keys and results until eviction or
clearing. maxsize=128 bounds the number of entries, not their byte size. A
cached bound method includes self in its key and can retain the instance.
Do not cache generator objects: a later hit would receive the same partly
consumed or exhausted iterator.
For the host lookup, decide how long a directory answer may be reused. A stable snapshot or version in the key can make reuse meaningful; a changing directory needs invalidation. Test correctness after a data change before celebrating a hit rate. Concurrent misses may also perform the same work more than once: cache coherence is not an exactly-once guarantee.
One-liner: partial and reduce
partial pre-fills some arguments and hands back a new callable — a closure
you don't have to write yourself:
reduce folds a sequence into one value by applying a two-argument function
repeatedly — useful for composing a pipeline of steps, though a plain sum()
or "".join() reads clearer for those specific jobs:
A cache's hit rate climbs toward 100% only once lookups start repeating —
100 * (x - k) / x, for x total lookups and k distinct keys held entirely
in the cache. Few distinct keys and many repeats is exactly where a cache earns
its memory; many distinct keys with few repeats is the thrashing case above.
Quick practice
from functools import partial
def power(base, exp):
return base ** exp
square = partial(power, exp=2)
cube = partial(power, exp=3)
print(square(5), cube(2))from functools import lru_cache
@lru_cache(maxsize=None)
def slow(n):
return n * n
slow(2); slow(2); slow(3)
before = slow.cache_info().hits
slow.cache_clear()
after = slow.cache_info().hits
print(before, after)🎯 Your turn
Write cached_lookup(keys, maxsize). Inside it, decorate the provided
resolve(key) with a fresh lru_cache(maxsize=maxsize), count how many
times the real resolve body runs, look up every key in order, and return:
{"work": <real calls>, "hits": <cache hits>, "misses": <cache misses>}
cached_lookup(["a", "b", "a", "a"], 2)→{"work": 2, "hits": 2, "misses": 2}cached_lookup(["a", "b", "c", "a"], 2)→{"work": 4, "hits": 0, "misses": 4}(the"a"was evicted)
maxsize may be None, meaning unbounded.
Hint: count the real work with a small closure around resolve (a
nonlocal counter, as in lesson 01), then
cache = lru_cache(maxsize=maxsize)(counting_resolve) makes a fresh cache
every run. Read hits and misses from cache.cache_info().
Press ▶ Run, then ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write a decorator remember(func) that keeps a dict of results keyed by the argument tuple and only calls func on a miss. real_calls(keys) wraps the provided slow_square and returns how many times its body actually ran for the given keys.
Given apply_rate(rate, amount) returning round(amount * (1 + rate / 100), 2), write taxed_all(rate, amounts) which uses functools.partial to fix the rate and returns the list of taxed amounts.
Write lru_by_hand(maxsize) returning a lookup(key) function that caches key.upper() for at most maxsize keys, evicting the least recently used key when full. Record each eviction. evictions(keys, maxsize) looks up every key and returns the evicted keys in order.
price_with_rate must be cached, but the rate changes during a run. Write quote_prices(requests) where each request is [price, rate]. Use a cached function whose arguments include the rate, so a changed rate can never return a stale answer. Return {"quotes": [...], "misses": n} where each quote is price + price * rate // 100.
Write run_pipeline(steps, text). Each step is [name, arg]: ["strip", null] strips, ["lower", null] lower-cases, ["replace", [old, new]] replaces, ["split", sep] splits, ["take", n] keeps the first n items. Build one function per step (use functools.partial for the ones with arguments), compose them with functools.reduce, and return the result.
A teammate wants to put @lru_cache(maxsize=None) on every function in Quarry "because it's free speed". Explain the conditions under which caching a function is safe, and describe two concrete ways it could make Quarry wrong or worse.