Memoization Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Memoization runs in O(1) cached time and O(n) space, in Python as in every other language.
- ✓functools.lru_cache(maxsize=n) and, since Python 3.9, functools.cache, which is exactly lru_cache(maxsize=None).
- ✓Decorate, do not hand-roll. Reach for @cache when the input domain is small and bounded (a config parse, a lookup table) and @lru_cache(maxsize=...) whenever it is not, so the cache cannot grow forever.
- ✓The Python trap: Arguments must be hashable, so passing a list or dict raises TypeError at CALL time, a caching decorator that works in every unit test and explodes on the one production path that passes a dict.
- ✓The hit path is implemented in C and never re-enters the interpreter, so a memoized call is typically faster than the cheapest pure-Python function body.
What Memoization actually is
Memoization in Python: what you actually reach for
Python implementation
from functools import cache, lru_cache
@lru_cache(maxsize=4096)
def levenshtein(a: str, b: str) -> int:
if not a:
return len(b)
if not b:
return len(a)
cost = 0 if a[-1] == b[-1] else 1
return min(
levenshtein(a[:-1], b) + 1,
levenshtein(a, b[:-1]) + 1,
levenshtein(a[:-1], b[:-1]) + cost,
)
levenshtein("kitten", "sitting")
print(levenshtein.cache_info())
# CacheInfo(hits=..., misses=..., maxsize=4096, currsize=...)
@cache # 3.9+, unbounded: only for small input domains
def parse_config(path: str) -> dict:
...Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1) cached
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Memoization?
functools.lru_cache(maxsize=n) and, since Python 3.9, functools.cache, which is exactly lru_cache(maxsize=None). Both are C-implemented decorators that build the key, store the result, and expose .cache_info() with hits, misses and current size plus .cache_clear(). For a method on a class, functools.cached_property memoizes a single value per instance instead.
What is the most common Python mistake when implementing Memoization?
Arguments must be hashable, so passing a list or dict raises TypeError at CALL time, a caching decorator that works in every unit test and explodes on the one production path that passes a dict. The second trap is decorating a method: self becomes part of the key and the cache holds a strong reference to it, so instances are never collected. The class leaks for the lifetime of the process.
How does Memoization actually perform in Python?
The hit path is implemented in C and never re-enters the interpreter, so a memoized call is typically faster than the cheapest pure-Python function body. Keyword arguments make the key more expensive to build than positional ones, and calling f(1) and f(x=1) produces two different cache entries for the same logical call. Time complexity is O(1) cached and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.