libb.memoize

memoize(obj)[source]

Decorator that caches function results based on arguments.

Stores function call results in a cache dictionary attached to the function itself, avoiding redundant computations for repeated calls with the same arguments.

Parameters:

obj (Callable[[ParamSpec(P)], TypeVar(R)]) – The function to memoize.

Return type:

Callable[[ParamSpec(P)], TypeVar(R)]

Returns:

A wrapped function with caching behavior.

Basic Usage:

>>> def n_with_sum_k(n, k):
...     if n==0:
...         return 0
...     elif k==0:
...         return 1
...     else:
...         less_n = n_with_sum_k(n-1, k)
...         less_k = n_with_sum_k(n, k-1)
...         less_both = n_with_sum_k(n-1, k-1)
...         return less_n + less_k + less_both

Memoization Speeds Up Recursive Calls:

>>> n_with_sum_k_mz = memoize(n_with_sum_k)
>>> n_with_sum_k_mz(3, 5)
61
>>> n_with_sum_k_mz.cache
{((3, 5), ()): 61}