Python

functools.cache Memoization

admin by @admin ADMIN
3m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Wrap any pure function with @cache (Python 3.9+) and get an unbounded memoization layer for free. Use @lru_cache(maxsize=N) when you need a bounded cache.
Python
Raw
from functools import cache, lru_cache

@cache                                     # unbounded
def fib(n: int) -> int:
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(100))                            # instant even though recursive
print(fib.cache_info())                    # CacheInfo(hits=98, misses=101, ...)

@lru_cache(maxsize=128)                    # bounded — evicts least-recently-used
def fetch_user(uid: int) -> dict:
    print(f"  fetching user {uid}…")
    return {"id": uid, "name": f"User {uid}"}

fetch_user(1); fetch_user(1); fetch_user(2)
# fetching user 1…
# fetching user 2…           ← only two real calls
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.