Registry / database / conditional-cache

conditional-cache

JSON →
library1.4pypypi✓ verified 35d ago

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.

database
Install & Compatibility
Where this runs

No compatibility data collected yet for this library.

Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

from conditional_cache import conditional_cache

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.

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()}")
Debug
Known footguns
gotchaThe `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.
gotchaArguments to `conditional_cache` (like `maxsize`, `typed`) are passed directly to `functools.lru_cache`. Understand `lru_cache`'s behavior regarding mutable arguments and cache invalidation.
gotchaIf 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.
Upgrade
Version history

Breaking-change detection hasn't run for this library yet.

Audit
Security & dependencies

CVE tracking and dependency tree are planned for a later release.

Agent activity
0 hits · last 30 days

No traffic data recorded yet.

Resources