Memoization is a powerful caching library for Python, providing decorators for function memoization with features like Time-To-Live (TTL) expiration, multiple caching algorithms (LRU, LFU, FIFO), and extensibility. It aims to solve some limitations of the standard library's `functools.lru_cache`, such as handling unhashable arguments. The library is actively developed, with its latest release being v0.4.0.
pip install memoizationVerified import paths — ran on the pinned version, not inferred.
Demonstrates basic memoization with TTL and a quick example of an LRU cache. The `cached` decorator automatically caches the function's return values, avoiding re-computation for the same inputs within the specified TTL or cache size.
Upgrade your Python environment to Python 3.4 or newer.
For versions `v0.4.0` and above, utilize the new cache manipulation APIs like `f.cache_clear(args=...)` for partial clearing, `f.cache_pop(args=...)`, or `f.cache_delete_if(condition_func)`.
In `v0.4.0`+, the `key_maker` no longer strictly needs the same signature. Always ensure your `key_maker` function deterministically produces unique and hashable keys that accurately represent the inputs for caching logic. Refer to the official documentation for best practices on custom key generation.
If the default `str()`-based key generation for unhashable arguments is not sufficient, provide a custom `key_maker` function that creates a robust, hashable key based on the relevant attributes or a deep hash of the unhashable inputs.
Upgrade to `memoization >= 0.1.4` and ensure the `thread_safe` parameter (if explicitly setting it) is configured appropriately for your application's concurrency model.
For arguments that are unhashable, use `memoization.cached` with a custom `key_maker` function. This function should transform the unhashable arguments into a consistent, hashable representation (e.g., a tuple of `frozenset`s or a JSON string) that uniquely identifies the function call. For example, if a list is a simple sequence, convert it to a tuple: `@cached(key_maker=lambda *args, **kwargs: (tuple(args[0]) if isinstance(args[0], list) else args[0],) + args[1:])`.
Import the correct decorator name, which is `cached`. The import statement should be `from memoization import cached`.
To inspect the cache or interact with it, use the specific methods provided by the `memoization` library. For example, use `my_function.cache_clear()` to clear the cache, or access internal statistics if exposed by the library's API (the `memoization` library's README mentions 'Cache statistics' but details specific methods for clearing, checking empty/full, not a direct `cache_info`). If more detailed introspection is needed, consult the library's documentation for equivalent functionality or access the `f.__wrapped__` if available and inspect the cache directly.
No dependency data recorded yet.