Lesson · Functional Programming Tools
functools
70 min readfunctools
`functools` collects function-oriented utilities for caching, partial application, dispatch, wrapping, and cached properties. Each tool addresses a specific composition or performance pattern.
Learning goals
- Explain what
@lru_cachestores and whyfib(30)returns quickly. - Build a specialized callable with
partialand name the arguments it freezes. - Read a memoized call and decide whether its arguments are hashable.
- Choose between
cacheand a boundedlru_cachefor a stated memory budget. - Register a type-specific implementation with
singledispatchand predict which branch runs.
Mental model
functools is a toolbox, not a pipeline: partial reshapes a callable, reduce folds data, and the cache decorators trade memory for repeated work. Every entry reads the same way: what it returns, what the caller keeps, and what must stay true between calls. The cache tools share one requirement (hashable arguments) and one failure mode (stale or unbounded results).
Core idea
Most of functools is one idea in different clothes: take a callable and produce a new callable that carries something extra. partial carries bound arguments, wraps carries metadata, and lru_cache carries a table of past results keyed by the arguments. The two cache decorators, lru_cache and cache, differ only in whether eviction bounds that table.
partial
partial creates a new callable with selected arguments pre-bound: partial(int, base=2) remembers base=2, so calling the result with "101010" runs int("101010", base=2). The wrapper stores those arguments and adds them to every call; it does not call the function yet.
reduce
reduce folds an iterable into one value by repeatedly combining an accumulator with the next item, beginning with the first item or an explicit initializer. It lives in functools because a plain loop is usually clearer, and folding an empty iterable with no initializer raises TypeError.
lru_cache
functools.lru_cache memoizes call results using arguments as cache keys. Cached arguments must be hashable, and cache policy must account for stale results and memory growth.
cache
functools.cache is lru_cache(maxsize=None): it memoizes every distinct argument combination and never evicts. That suits small, stable argument sets; without eviction the table grows for the lifetime of the process.
cached_property
cached_property computes a value once on first access and stores it in the instance dictionary under the same name. Later accesses read the stored value, so the instance needs a normal mutable namespace and the cached value never expires.
singledispatch
singledispatch turns a function into a generic one that dispatches on the runtime type of its first argument. Register implementations with @name.register(SomeType), and the base implementation handles anything unmatched.
wraps
functools.wraps copies metadata such as __name__, __doc__, and __module__ from a wrapped function to its wrapper and sets __wrapped__. Use it inside every hand-written decorator so debugging and introspection describe the original function.
Cache keys and hashability
A memoized call is stored under a key derived from its arguments, so every argument must be hashable: fib(30) keys on an int, while passing a list raises TypeError: unhashable type: 'list'. Arguments that compare equal and hash equal share one entry, which is why 1 and True would hit the same cache slot.
Cache hits vs misses
A cache hit returns the stored result without running the body; a miss runs the body and records the result for next time. The hit rate grows with repeated keys, which is why the naive recursion in fib collapses from exponential to linear work once the decorator is present.
Bounded vs unbounded caches
A bounded cache such as lru_cache(maxsize=128) evicts the least recently used entry when full, so memory stays fixed. An unbounded cache (cache or maxsize=None) keeps every result forever, which is simpler to reason about but grows with the number of distinct keys.
Cache invalidation concerns
A cache is correct only while cached results remain valid. Define which inputs form the key, when data becomes stale, and how memory growth is bounded.
When memoization is appropriate
Memoization pays when the same inputs recur and the function is pure, meaning the result depends only on the arguments; repeated fib subproblems are the textbook case. It backfires on side-effecting or time-dependent functions, where a stored result goes stale, and on argument sets so wide that entries are never reused.
Walkthrough
fibcalls itself, so without a cache the same small values would be recomputed down many branches;@lru_cache(maxsize=128)runs the body once per distinctnand answers every repeat from the table.partial(int, base=2)storesintand the keywordbase=2; callingbase2("101010")forwards the string plus the stored keyword, sobase2("101010")andint("101010", base=2)agree.- The printed values are
832040and42.singledispatchis imported but unused here, a reminder that the module ships more tools than one example can show. - Predict before running: which number prints first, and why
base2("101010")is not101010.
Experiments to try
- Read
fib.cache_info()before and afterfib(30); record hits and misses and connect them to the recurrence. - Add a print inside
fib, callfib.cache_clear(), and count body executions forfib(30); compare with the same count without the decorator. - Call
base2("11111111")andint("11111111", base=2); verify equality, then trybase2("12")and read theValueError. - Write a small
singledispatchfunction with implementations forintandstr, call it with each, then call it withTrueand explain which implementation wins.
Common mistakes
- Decorating a function whose arguments are unhashable: the cache lookup raises
TypeErrorbefore the body runs, so a working function fails only after the decorator is added. - Assuming
lru_cachenotices outside changes: results are stored against argument values, so a function that reads time, files, or mutable state returns stale answers. - Forgetting
functools.wrapsin a hand-written decorator, which hides the original__name__and breakshelp()output. - Using
reducefor an accumulation thatsum,join, or an explicit loop reads more clearly; the utility fits genuine pairwise combination, not every fold.
Practice: Easy
- Run the worked example, call
fib(30)a second time, and readfib.cache_info(); explain which counter changed. - Create
hex2 = partial(int, base=16)and convert"ff"; then callbase2("101010", base=10)and explain the resulting error. - Call
base2("12")and read theValueError; state which layer rejected the input and why.
Practice: Medium
- Write a memoized
count_paths(m, n)for grid moves; verify the recomputation difference withcache_info()on a 10 by 10 grid and state what the cache key contains. - Write
size_forwithsingledispatch: one implementation forlist, one forstr, and a base for anything else; call it with all three kinds of argument. - Time
fib(32)withmaxsize=128, withmaxsize=None, and withmaxsize=4; usecache_info()to say which change affects runtime and which affects peak cache size.
Practice: Hard
- Design a memoized recursive solution for the edit distance between two strings; define the key, the eviction policy, and a test that shows hits and misses on two related inputs.
- Replace
reducewith an explicit loop in one example, then find a case wherereducereads better (for example intersecting several sets); justify the choice for a reviewer. - Build a dispatch table with
singledispatchfor config parsing (str,int,list), extend it tobool, and explain how method resolution order decides which implementation wins for subclasses.
Lesson checklist
- I can say what
@lru_cachestores and when it recomputes. - I can build
partial-based helpers and name the frozen arguments. - I can choose between
cacheand a boundedlru_cacheand justify the memory tradeoff. - I can register
singledispatchimplementations and predict the branch selected for a subclass.
Remember
`functools` produces new callables that carry extra machinery: bound arguments in `partial`, metadata in `wraps`, a results table in `lru_cache` and `cache`, and type-directed behavior in `singledispatch`. Memoization keys must be hashable and results must not go stale, and the bounded form caps memory while the unbounded form does not. Match the tool to the contract the caller expects.
Interview angles
What is the main purpose of **partial**?+
partial creates a new callable with selected arguments pre-bound: partial(int, base=2) remembers base=2, so calling the result with "101010" runs int("101010", base=2). The wrapper stores those arguments and adds them to every call; it does not call the function yet.
What should you pay attention to when using **reduce**?+
reduce folds an iterable into one value by repeatedly combining an accumulator with the next item, beginning with the first item or an explicit initializer. Folding an empty iterable with no initializer raises TypeError.
How does **lru_cache** fit into this lesson?+
functools.lru_cache memoizes call results using arguments as cache keys. Cached arguments must be hashable, and cache policy must account for stale results and memory growth.
Why does `@lru_cache` reject a list argument?+
The cache key must be hashable, and lists are mutable and therefore unhashable, so the call raises TypeError: unhashable type: 'list' before the function body runs. Convert the data to a tuple for the call, or design a key you build yourself.