Conditional Cache

1.4 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

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()}")

view raw JSON →