functools.lru_cache
A Python decorator from the functools module that memoises a function, remembering results for arguments it has seen.
In more detail
With maxsize=None the cache grows without limit; with a number it keeps only that many recent results and evicts the least recently used. Arguments must be hashable, because they become dict keys. Adding it to naive Fibonacci turns an exponential function into a linear one.
Example
@functools.lru_cache(maxsize=None)Related terms
- memoisation — Caching a function's results by its arguments so that repeated calls return the stored answer instead of recomputing it.
- LRU cache — A fixed-size cache that, when full, throws out the entry that has gone unused the longest.
- decorator — A line starting with @ placed above a function or class that wraps it to add behaviour or information.
- hashable — Describes a Python object that has a hash value that never changes during its lifetime and can be compared for equality, so it can be a dict key or set member.
Taught in
- Dynamic Programming: Memoisation And Tabulation — Algorithms & Data Structures for Working Engineers