Registry / database / cachier

cachier

JSON →
library4.2.0pypypi✓ verified 89d ago

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.

pip install cachier
INSTALL
IMPORT
SIG · CACHIER
C
cachier
databasepythonv4.2.0
Install
3.8s avg
Import
905ms
Disk
78MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v4.2.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.940 runs
installs and imports cleanly · install 0.0s · import 0.926s · 90.5MB
glibc
py 3.10–3.940 runs
installs and imports cleanly · install 3.8s · import 0.884s · 91MB
78MB installed
● package 78MB
Code
Verified usage

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

cachier
✓ from cachier import cachier
set_global_params
✓ from cachier import set_global_params
✗ from cachier import set_default_params
The `set_default_params` function is deprecated; use `set_global_params` instead for configuring global parameters.

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()
Debug
Known issues
breakingStarting with v3.0.0, cache keys now consider the function's name. If you upgrade from versions prior to 3.0.0 and relied on cache keys being agnostic to function names (e.g., if you copied and renamed functions), your existing cache entries might not be found or could cause collisions.
fix
Be aware of this change when upgrading. Existing cache entries might need to be cleared or regenerated if function names were not implicitly part of your keying strategy.
affects: <3.0.0 to 3.0.0+
breakingIn v4.0.0, the `enable_caching()` and `disable_caching()` global functions now correctly affect *all* existing `@cachier` decorators. Previously, they might not have had an effect on decorators already applied. Additionally, `cachier` adopted the XDG Base Directory Specification for cache file locations, which might change the default cache directory (e.g., from `~/.cachier` to `~/.cache/cachier` on Linux).
fix
If using global enable/disable, verify its behavior after upgrading. If relying on cache file locations, check `~/.cache/cachier` (or `$XDG_CACHE_HOME/cachier`) and potentially migrate existing cache files.
affects: <4.0.0 to 4.0.0+
gotchaBy default, `cachier` will raise a `TypeError` when decorating an instance method (a method whose first parameter is named `self`). This is to prevent unintended cross-instance cache sharing. If you explicitly want cross-instance cache sharing for a method, you must pass `allow_non_static_methods=True` to the decorator.
fix
For instance methods, use `@cachier(allow_non_static_methods=True)` or ensure the method is a `@staticmethod` or `@classmethod` if shared caching is not desired.
affects: All versions
gotchaFunctions decorated with `cachier` require all positional and keyword arguments to be hashable Python objects. If an unhashable argument is passed (e.g., a list or dictionary), a `TypeError` will be raised.
fix
Ensure all arguments to cached functions are hashable. For functions with unhashable arguments, consider providing a custom `hash_func` to the decorator to generate a hashable key from the unhashable inputs.
affects: All versions
gotchaAsynchronous functions decorated with `cachier` will have their operations delegated to the synchronous implementation for many backends. Starting with v4.2.0, decorating async methods with sync-only engines of Redis, Mongo, and SQL cores is restricted and may lead to errors or unexpected behavior.
fix
For optimal and correct async caching, ensure you are using backends and client configurations that natively support async operations, or understand the delegation behavior for your chosen backend.
affects: 4.2.0+
gotchaBy default, `cachier` does not cache `None` values returned by a function. If your function can legitimately return `None` and you wish to cache it, you must explicitly enable this behavior.
fix
Pass `allow_none=True` to the decorator: `@cachier(allow_none=True)`.
affects: All versions
Errors
Common errors & fixes
TypeError: Cannot decorate instance methods without 'allow_non_static_methods=True'.
Cachier, by default, prevents caching of instance methods (functions with 'self' as the first parameter) to avoid unexpected behavior related to cross-instance cache sharing.
fix
To explicitly allow caching of instance methods, pass `allow_non_static_methods=True` to the `@cachier` decorator. Ensure this is the desired behavior, as it means the cache will be shared across all instances of the object.

```python
from cachier import cachier

class Foo:
    @cachier(allow_non_static_methods=True)
    def my_method(self, arg1):
        return arg1 * 2
```
Function return value is None, but cachier is not caching it.
By default, Cachier does not cache `None` values, which can lead to unexpected cache misses if a function is expected to legitimately return `None`.
fix
To instruct Cachier to cache `None` values, set `allow_none=True` in the `@cachier` decorator.

```python
from cachier import cachier

@cachier(allow_none=True)
def function_returning_none(arg):
    if arg > 0:
        return arg
    return None
```
redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection refused.
This error indicates that the Python application cannot establish a connection with the Redis server, often because the server is not running, is configured to listen on a different address/port, or a firewall is blocking the connection.
fix
Verify that the Redis server is running and accessible from the application's environment. Check the Redis configuration for the correct host and port, ensure no firewalls are blocking the connection (e.g., port 6379 for Redis), and confirm `cachier` is configured with the correct client or connection string for Redis.

```python
# Example for Redis in cachier, assuming redis_client is correctly initialized
import redis
from cachier import cachier

# Ensure your Redis server is running, e.g., 'redis-server'

# Example of setting up cachier with a Redis client
REDIS_CLIENT = redis.StrictRedis(host='localhost', port=6379, db=0)

@cachier(backend='redis', redis_client=REDIS_CLIENT)
def my_cached_function_redis():
    return "Data from Redis"
```
OSError: inotify instance limit reached
This error occurs on Linux systems when the default pickle backend of Cachier attempts to create too many `inotify` watches, typically when caching a very large number of distinct functions or keys, exceeding the system's `fs.inotify.max_user_watches` limit.
fix
Increase the system's `inotify` watch limit. This is a system-level configuration, not a `cachier` code fix. Alternatively, consider using a different `cachier` backend like MongoDB or Redis if you anticipate a very large number of cached items, as they don't rely on `inotify` for cache file monitoring.

```bash
# To increase the inotify watch limit (e.g., to 524288)
# Add this line to /etc/sysctl.conf
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf

# Apply the change
sudo sysctl -p
```
Upgrade
Version history
4.2.0latest on PyPI · released Mar 26, 2026
Audit
Dependencies
portalockerrequiredCore dependency for robust file locking in pickle backend.
watchdogoptionalOptional dependency for more efficient file system event monitoring in pickle backend, especially on Linux.
pymongooptionalRequired for the MongoDB caching backend.
redisoptionalRequired for the Redis caching backend.
sqlalchemyoptionalRequired for the SQL (SQLAlchemy) caching backend.
boto3optionalRequired for the S3 caching backend.
Agent activity
24 hits · last 30 days
node
18
Amazon
2
OpenAI (training)
1
Resources
cachier — pip install cachier · libregistry