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
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
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.