@cache#
Unbounded memoization decorator in functools (Python 3.9+, equivalent to @lru_cache(maxsize=None)). Caches return values keyed by function arguments so repeated calls with identical arguments return in O(1).
Basic Usage#
Eliminates redundant recursive calls in top-down dynamic programming without manually managing a memo array or map.
eg.
from functools import cache
@cache
def fib(n: int) -> int:
if n <= 1:
return n
return fib(n - 1) + fib(n - 2) # O(N) instead of O(2^N)- Bounded Cache: When argument space is unbounded in long-running services, use
@lru_cache(maxsize=1024)instead to cap memory usage. - Cache Management: Clear stored entries with
fib.cache_clear()or inspect hit/miss counts withfib.cache_info().
Internal Mechanism#
Under the hood, @cache packs positional arguments into a tuple and uses it as the key of an internal dict. See *args and **kwargs.
def simple_cache(func):
memo = {} # Internal dict storing cached results
def wrapper(*args):
# eg. calling fib(5) sets args = (5,)
if args in memo: # 1. O(1) lookup using args tuple as dict key
return memo[args]
res = func(*args) # 2. Compute only on cache miss
memo[args] = res # 3. Store result in memo[args]
return res
return wrapperHashable Argument Requirement#
Because args is stored as a dict key, every argument must be hashable (immutable with a fixed hash() value).
dictis implemented as a hash table, yet adictinstance itself is mutable and therefore unhashable (__hash__ = None) — mutating it after insertion would invalidate its hash bucket.
| Category | Hashable (@cache allowed) | Unhashable (TypeError) | Conversion |
|---|---|---|---|
| Scalar | int, float, bool, str, bytes | - | - |
| Sequence | tuple (with hashable elements) | list | tuple(lst) |
| Set | frozenset | set | frozenset(s) |
| Mapping | - | dict | tuple(sorted(d.items())) |
eg.
from functools import cache
@cache
def sum_values(items: tuple[tuple[str, int], ...]) -> int:
return sum(v for _, v in items)
d = {"a": 1, "b": 2}
ans = sum_values(tuple(sorted(d.items())))Nested Function Pattern for Algorithms#
When solving problems over an input list, define the @cache helper inside the outer function:
- Reads the outer
listvia closure while passing onlyintstate indices as@cachearguments. - Automatically garbage-collects the cache
dictwhen the outer function returns, preventing cross-test contamination.
eg.
from functools import cache
def rob_houses(nums: list[int]) -> int:
@cache
def dfs(i: int) -> int:
if i >= len(nums):
return 0
return max(nums[i] + dfs(i + 2), dfs(i + 1))
return dfs(0)