Skip to content

Memoization

The rite.functional.memoization submodule provides helpers for caching function results and building simple LRU-like caches.

Memoization Module

Function result caching utilities.

This submodule provides decorators for memoizing function results with various caching strategies.

Examples

from rite.functional.memoization import ( ... memoization_memoize, ... memoization_lru_cache ... ) @memoization_memoize() ... def fibonacci(n): ... if n <= 1: ... return n ... return fibonacci(n-1) + fibonacci(n-2)

Modules

memoization_lru_cache

LRU Cache

Least Recently Used cache with size limit.

Examples

from rite.functional.memoization import memoization_lru_cache @memoization_lru_cache(maxsize=128) ... def compute(n): ... return n * n

Functions

memoization_lru_cache(maxsize: int | None = 128) -> Callable[[Callable[..., T]], Callable[..., T]]

LRU cache decorator with size limit.

Parameters:

Name Type Description Default
maxsize int | None

Maximum cache size (None for unlimited).

128

Returns:

Type Description
Callable[[Callable[..., T]], Callable[..., T]]

Decorated function with LRU caching.

Examples:

>>> @memoization_lru_cache(maxsize=100)
... def factorial(n):
...     if n <= 1:
...         return 1
...     return n * factorial(n - 1)
>>> factorial(5)
120
Notes

Uses functools.lru_cache internally. Set maxsize=None for unlimited cache.

memoization_memoize

Simple Memoization

Cache function results based on arguments.

Examples

from rite.functional.memoization import memoization_memoize @memoization_memoize() ... def fibonacci(n): ... if n <= 1: ... return n ... return fibonacci(n-1) + fibonacci(n-2)

Functions

memoization_memoize() -> Callable[[Callable[..., T]], Callable[..., T]]

Decorator to memoize function results.

Caches results based on arguments.

Returns:

Type Description
Callable[[Callable[..., T]], Callable[..., T]]

Decorated function with caching.

Examples:

>>> @memoization_memoize()
... def expensive_computation(n):
...     return sum(range(n))
>>> expensive_computation(100)
4950
>>> expensive_computation(100)  # Returns cached result
4950
Notes

Only works with hashable arguments. For unhashable args, use custom cache key.

options: show_root_heading: true show_source: false heading_level: 2