Conditional Cache
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.
Common errors
-
TypeError: conditional_cache() missing 1 required positional argument: 'condition_func'
cause The `@conditional_cache` decorator requires the `condition_func` keyword argument to be explicitly provided.fixAlways pass a function or lambda to `condition_func` within the decorator, e.g., `@conditional_cache(condition_func=my_condition_func)`. -
ValueError: The `condition_func` must return a boolean value.
cause Your `condition_func` returned a value that is not `True` or `False` (e.g., `None`, an integer, a string).fixModify 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`. -
AttributeError: 'function' object has no attribute 'cache_info'
cause You are trying to access `cache_info()` or `cache_clear()` on a non-decorated function or before the decorator has been correctly applied/initialized.fixEnsure 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()`.
Warnings
- gotcha The `condition_func` must return a boolean value (`True` or `False`). If it returns a non-boolean, a `ValueError` will be raised when the function is called.
- gotcha Arguments to `conditional_cache` (like `maxsize`, `typed`) are passed directly to `functools.lru_cache`. Understand `lru_cache`'s behavior regarding mutable arguments and cache invalidation.
- gotcha If the `condition_func` has side effects or takes a long time to execute, it will impact the performance of every function call, whether cached or not, as it runs *after* the wrapped function and *before* the caching decision.
Install
-
pip install conditional-cache
Imports
- conditional_cache
from conditional_cache import conditional_cache
Quickstart
from conditional_cache import conditional_cache
import time
# Define a condition: only cache results greater than 0
def cache_if_positive(result):
return result > 0
@conditional_cache(condition_func=cache_if_positive, maxsize=128)
def compute_value(x, y):
print(f"Computing {x} + {y}...")
time.sleep(0.1) # Simulate work
return x + y
print("--- First call (result > 0, should cache) ---")
print(f"Result: {compute_value(1, 2)}") # Computes, caches
print(f"Result: {compute_value(1, 2)}") # From cache
print("\n--- Second call (result <= 0, should NOT cache) ---")
print(f"Result: {compute_value(-1, 0)}") # Computes, does not cache
print(f"Result: {compute_value(-1, 0)}") # Computes again
print(f"Cache Info: {compute_value.cache_info()}")