Conditional Cache is a Python library that provides a decorator for conditionally caching function results. It wraps `functools.lru_cache`, allowing caching only if a specified `condition_func` returns `True` based on the function's output. The current version is 1.4, and its release cadence is driven by bug fixes and feature enhancements, maintaining a stable API.
pip install conditional-cacheVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to use the `conditional_cache` decorator. The `compute_value` function will only cache its result if the `cache_if_positive` function returns `True` for that result. Notice how `compute_value(-1, 0)` is computed twice because its result ( -1) does not satisfy the caching condition.
Ensure your `condition_func` explicitly returns `True` to cache or `False` to not cache. For example, `lambda result: result is not None`.
Review `functools.lru_cache` documentation to understand how it handles arguments and what causes cache misses, especially with default `typed=False`.
Design your `condition_func` to be lightweight, pure, and quick to execute. Avoid complex logic or external calls within it.
Always pass a function or lambda to `condition_func` within the decorator, e.g., `@conditional_cache(condition_func=my_condition_func)`.
Modify your `condition_func` to guarantee a `True` or `False` return. For instance, `return result is not None` instead of `return result` if `result` could be `None`.
Ensure the function is correctly decorated with `@conditional_cache(...)` and that you are calling these methods on the decorated function object, e.g., `my_function.cache_info()`.
No dependency data recorded yet.