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.

PythonData Fetching

Code

snippet
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())