Cache function results with functools.lru_cache
Memoize pure functions with a bounded least-recently-used cache and inspect or clear it.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
from functools import lru_cache
@lru_cache(maxsize=256)
def fibonacci(n):
return n if n < 2 else fibonacci(n - 1) + fibonacci(n - 2)Example / expected output
fibonacci(80) # 23416728348467685, computed in microsecondsHow it works
lru_cache is in the standard library, thread-safe and fast. Arguments must be hashable. Always set maxsize for functions with many distinct inputs, otherwise memory grows without bound. cache_info() shows hits and misses; cache_clear() resets it.
Related snippets
- JavaScript Tested
Conditional GET with ETag and 304
Compute a strong ETag for a response body and answer If-None-Match with 304 Not Modified to save bandwidth.
- Python Tested
Time a block of code with a context manager
Measure elapsed wall-clock time of a with-block using time.perf_counter.
- PHP Tested
Read a large CSV file with a generator
Stream CSV rows as associative arrays using fgetcsv, without loading the whole file into memory.
- JavaScript Tested
Run async tasks with a concurrency limit
Process a large list with at most N promises in flight at once, preserving result order.

