Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Memoization in Python with functools.lru_cache

Plenty of Python programs spend most of their runtime recalculating answers they have already worked out. A parser that re-reads the same configuration, a pricing rule applied to the same postcode all afternoon, a recursive solver that walks the same branch of a tree twice — these are exactly the situations memoization was designed for. The idea is straightforward: remember the result of a call the first time you see a particular set of arguments, then return the stored result on every later request.

Python ships this idea in the standard library, so there is no need to hunt for a third-party package or hand-roll a dictionary-backed decorator. The functools module provides lru_cache, a decorator that wraps a function and keeps its return values in an internal mapping keyed by the arguments it receives. Applied to a single line of code, it can pull an exponential algorithm back to something tractable, shave seconds off a data pipeline, or make a test suite finish before the kettle boils. The rest of this piece covers how the decorator behaves, where it genuinely helps, and where it quietly gets in the way.

What lru_cache actually does

Decorating a function with @lru_cache changes nothing about how you call it. Internally, the wrapper builds a key from the positional and keyword arguments, checks an internal dictionary-like structure for that key, and returns the stored value if it finds one. On a miss, it calls the original function, saves the result against the key, and hands it back. Because the key comes from a hash, the lookup averages around O(1), which is cheap next to almost any calculation you would prefer not repeat. The original function still exists; the decorator simply sits in front of it.

One subtlety catches people out: the key depends on how the arguments were passed. A call such as f(2) and another such as f(x=2) can occupy two separate entries even though the values match, quietly halving your hit rate and doubling the memory used. Standardising on one calling style across a codebase is a cheap improvement. The wrapper also holds a reference to the original function for as long as the decorated name exists, and since Python 3.9 the standard library offers functools.cache, which is shorthand for lru_cache(maxsize=None) and never evicts anything.

Memoizing recursion and dynamic programming

The classic demonstration is the Fibonacci sequence. Written as plain recursion, each call spawns two more calls, and the number of evaluations grows exponentially with n.

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n: int) -> int:
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

The base case, where n is below two, returns the value directly. Everything above it asks the decorated function for its two smaller neighbours, and because each result is now stored, fib(30) computes each value once instead of thousands of times. Time complexity drops from roughly O(φⁿ) to O(n), while the cache grows linearly with n. The code barely changed, and that is the appeal of memoization in dynamic programming: describe the recurrence once and let the decorator handle the bookkeeping.

Australian product teams meet the same wall eventually, whether they build at Atlassian and Canva in Sydney or at REA Group and Culture Amp in Melbourne. Overlapping subproblems, repeated work, and a cache between the caller and the calculation look the same wherever the code lives.

Bounding the cache with maxsize

The default limit is 128 entries, and once the cache fills up, adding a new key evicts the least recently used entry, which is where the lru in the name comes from. Passing maxsize=None removes the limit entirely, while a specific number such as 256 gives a predictable upper bound. The decorator also exposes two useful methods on the wrapped function.

@lru_cache(maxsize=256)
def quote(postcode: str) -> dict:
    return shipping_rates_for(postcode)

quote.cache_info()   # CacheInfo(hits=..., misses=..., maxsize=256, currsize=...)
quote.cache_clear()

cache_info reports hits, misses, the current size, and the limit, and from Python 3.8 onwards the same result carries a hit_rate property. Reading those numbers after a representative run shows whether the cache is doing work or merely occupying memory. Each entry carries the key, the value, and dictionary overhead, so a few thousand entries disappear into the background while a few million do not, particularly on shared CI runners with tighter limits. When memory traffic is the real constraint, algorithmic restraint pays too — a cycle sort guide shows how sorting with minimal writes reduces the cost of moving data around.

Hashable arguments and other limits

Everything the decorator stores must be hashable, because the arguments form the key. Strings, numbers, tuples, and frozen dataclasses work. Lists, dictionaries, and sets do not, and passing one raises a TypeError straight away. The usual fix is to convert the data before calling: accept a list but cache an internal helper that takes a tuple, or use a frozenset when order does not matter. Return values impose no such restriction, since only the inputs are hashed.

Hashable is not the same as safe to cache. A function that reads a file, queries a database, or depends on the current time can return a different answer for identical arguments, and the decorator will happily serve the stale one. Functions that mutate global state are equally awkward, because the cached result skips work the caller may have relied on. If a returned dictionary gets edited in place, later callers receive the edited object, so copy mutable results before handing them out. Caching methods needs care as well, since self becomes part of the key and keeps every instance the decorator has ever seen alive.

Measuring the speedup

Timing a decorated function against the undecorated original is easy with timeit, and it is worth doing on realistic inputs, because a benchmark over a single value measures the cache hit path and nothing else. Include cache misses deliberately, and run the comparison on the hardware you actually ship on rather than on a workstation with a much faster CPU. Australian data-heavy work, from regulatory datasets at ASIC in Sydney to the engineering groups at ANZ, often sits behind exactly this kind of repeated lookup.

Some functions should not be cached at all. Large vectorised array operations spend their time in memory bandwidth rather than Python-level overhead, and the fix there is a better expression of the maths rather than a dictionary. This NumPy broadcasting guide covers how to reshape and combine arrays so the work happens in fewer passes.

A second measurement matters more than the clock: the hit rate reported by cache_info. A function whose misses keep climbing while hits stay flat is either being called with constantly new arguments or is not the right candidate at all. Track that ratio across a realistic request mix before tuning maxsize.

Caching in games and graph search

Game AI is a natural home for memoization. Simulations repeat similar states, evaluations repeat similar positions, and both are expensive enough to be worth remembering. The techniques described in Monte Carlo tree search rely on running many rollouts from a shared set of states, and a cache keeps repeated evaluations of the same position from being recomputed. Studios around Brisbane and Melbourne building strategy or puzzle games find that the same principle applies to pathfinding tables as much as to board evaluation.

Graph algorithms benefit for the same reason. A router calculating a path between two Australian cities may ask about the same pair of junctions repeatedly as it explores alternatives, and a cache keyed on the node pair avoids recomputing identical subpaths. Shortest-path implementations from Dijkstra onwards all hide a memo table somewhere, and lru_cache lets you express that table in one line instead of a mutable dictionary threaded through five functions. The rule of thumb is simple: if two calls with the same inputs produce the same output, and the calculation costs more than a hash lookup, caching is likely to pay for itself.

Caching patterns worth adopting

A handful of habits cover most of the value people get from this decorator, and each of them is easy to check during code review.

For a practical look at how these ideas land in real codebases, the community meetups and PyCon AU's visits to Sydney and Melbourne regularly cover caching, profiling, and the tooling around them. The decorator itself has lived in the standard library for years, so there is no dependency to justify and no vendor to evaluate. Add the one line, watch the hit rate, and let the rest of the afternoon — even an arvo in Melbourne with a flat white in hand — get back to the code that actually needed writing.