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())Report a problem with this exampleOpens a pre-filled issue on GitHub.