Persistent, Stale-Free Caching for Python Functions

4.2.0 · active · verified Wed Apr 15

Cachier is a Python library that provides persistent, stale-free memoization decorators for Python functions. It supports various storage backends including local filesystem (pickle), in-memory, MongoDB, Redis, SQL, and S3, offering configurable cache expiration and automatic invalidation. The library is actively maintained with frequent releases, currently at version 4.2.0, and supports both synchronous and asynchronous functions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `cachier` decorator to add a persistent, time-based cache to a Python function. The first call computes the result, and subsequent calls within the `stale_after` period return the cached value instantly. It also shows how to manually clear a function's cache.

from cachier import cachier
from datetime import timedelta

@cachier(stale_after=timedelta(days=1))
def long_running_function(arg1, arg2):
    """This function's result will be cached for 1 day."""
    print(f"Calculating result for {arg1}, {arg2}...")
    # Simulate a long computation
    import time
    time.sleep(1)
    return arg1 + arg2

# First call: calculates and caches the result
print(f"Result 1: {long_running_function(10, 20)}")

# Second call (within 1 day): returns from cache instantly
print(f"Result 2: {long_running_function(10, 20)}")

# To clear the cache for a specific function:
long_running_function.clear_cache()

view raw JSON →