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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A closure lets a decorator hold private per-function state like a cache across calls.
- 2Keying a cache on the argument tuple turns repeated calls into instant dictionary lookups.
- 3Memoizing a recursive function collapses its exponential call tree down to linear work.
Related explainers
python
import argparse import sys from pathlib import Path
Building a subcommand CLI with argparse
cli
argparse
subcommands
Intermediate
6 steps
ruby
require "csv" class SalesReport def initialize(path)
Aggregating CSV sales data in Ruby
data-aggregation
memoization
group_by
Intermediate
6 steps
python
from collections.abc import Mapping from typing import Any, Iterator
Flattening nested config into dotted keys
recursion
generators
tree-traversal
Intermediate
7 steps
python
import csv import io from datetime import datetime
Streaming a CSV export in Flask
streaming
generators
csv
Intermediate
9 steps
python
import time from collections import defaultdict from threading import Lock
Sliding-window login rate limiting in Flask
rate-limiting
sliding-window
thread-safety
Intermediate
7 steps
javascript
const RATE_LIMIT = 100; const WINDOW_MS = 60 * 1000; const BLOCK_MS = 5 * 60 * 1000;
Building a rate-limiting middleware in Express
rate-limiting
middleware
closures
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-memoize-decorator-in-python-explained-python-4cc6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.