stouputils.decorators.simple_cache module#

simple_cache(
func: Callable[..., T],
*,
method: Literal['str', 'pickle'] | Callable[[tuple[Any, ...], dict[str, Any]], Any] = 'str',
) Callable[..., T][source]#
simple_cache(
func: None = None,
*,
method: Literal['str', 'pickle'] | Callable[[tuple[Any, ...], dict[str, Any]], Any] = 'str',
) Callable[[Callable[..., T]], Callable[..., T]]

Decorator that caches the result of a function based on its arguments.

The str method is often faster than the pickle method (by a little) but not as accurate with complex objects.

Parameters:
  • func (Callable[..., T] | None) – Function to cache

  • method (Literal["str", "pickle"]) – The method to use for caching.

Examples

>>> @simple_cache
... def test1(a: int, b: int) -> int:
...     return a + b
>>> @simple_cache(method="str")
... def test2(a: int, b: int) -> int:
...     return a + b
>>> test2(1, 2)
3
>>> test2(1, 2)
3
>>> test2(3, 4)
7

Cache a recursive function: >>> @simple_cache … def factorial(n: int) -> int: … return n * factorial(n - 1) if n else 1 >>> factorial(10) # no previously cached result, makes 11 recursive calls 3628800 >>> factorial(5) # no new calls, just returns the cached result 120 >>> factorial(12) # two new recursive calls, factorial(10) is cached 479001600

Prevent a function from running more than once regardless of arguments: >>> @simple_cache(method=lambda x, y: 1) … def execute_one_time() -> None: … print(“Executed!”) >>> _ = [execute_one_time() for _ in range(3)] Executed!