Least-Recently-Used Cache Decorator
Apply a bounded least-recently-used cache to a pure function so repeated calls with the same arguments skip recomputation.
Code
import functools
from typing import Callable, TypeVar
T = TypeVar("T")
def memoize(maxsize: int = 128) -> Callable[[Callable[..., T]], Callable[..., T]]:
def decorator(func: Callable[..., T]) -> Callable[..., T]:
cached = functools.lru_cache(maxsize=maxsize)(func)
cached.cache_info = cached.cache_info # expose cache statistics
return cached
return decorator
@memoize(maxsize=64)
def fib(n: int) -> int:
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(30))
print(fib.cache_info())Output
Captured from a sandboxed run of this snippet in the build pipeline.
832040
CacheInfo(hits=28, misses=31, maxsize=64, currsize=31)Inside the snippet
Count the functions memoize, decorator and fib as the entire surface area of Least-Recently-Used Cache Decorator.
Using it
The primary signature is def memoize(maxsize: int = 128) -> Callable[[Callable[..., T]], Callable[..., T]]
memoize is what another module would consume; nothing else here is load-bearing for callers.
Key statements
def decorator(func: Callable[..., T]) -> Callable[..., T]:
cached = functools.lru_cache(maxsize=maxsize)(func)
cached.cache_info = cached.cache_info # expose cache statistics
return cached
def fib(n: int) -> int:
return n if n < 2 else fib(n - 1) + fib(n - 2)
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `functools`, `typing`. The file defines `memoize`, `decorator`, `fib` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.