python 21 lines · 5 steps

Building a memoize decorator in Python

A decorator caches function results by their arguments so expensive calls run only once.

Explained by highlit
1from functools import wraps
2 
3 
4def memoize(func):
5 cache = {}
6 
7 @wraps(func)
8 def wrapper(*args):
9 if args not in cache:
10 cache[args] = func(*args)
11 return cache[args]
12 
13 wrapper.cache = cache
14 return wrapper
15 
16 
17@memoize
18def fibonacci(n):
19 if n < 2:
20 return n
21 return fibonacci(n - 1) + fibonacci(n - 2)
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A closure lets a decorator hold private per-function state like a cache across calls.
  2. 2Keying a cache on the argument tuple turns repeated calls into instant dictionary lookups.
  3. 3Memoizing a recursive function collapses its exponential call tree down to linear work.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a memoize decorator in Python — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code