Registry / database / cashews

cashews

JSON →
library7.5.0pypypi✓ verified 86d ago

Cashews is a Python library providing asynchronous cache tools, designed to help build fast and reliable applications. It supports multiple storage backends like in-memory, Redis, and DiskCache, offering a decorator-based API and various caching strategies. The current version is 7.5.0, and it maintains an active release cadence with regular updates and community support.

pip install cashews
INSTALL
IMPORT
SIG · CASHEWS
C
cashews
databasepythonv7.5.0
Install
1.9s avg
Import
336ms
Disk
22MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v7.5.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.103.9100 runs
installs and imports cleanly · install 0.0s · import 0.357s · 23.3MB
glibc
py 3.103.9100 runs
installs and imports cleanly · install 1.9s · import 0.315s · 24MB
22MB installed
● package 22MB
Code
Verified usage

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

cache
from cashews import cache

This quickstart demonstrates setting up Cashews with a Redis backend (or in-memory if Redis is unavailable) and using the `@cache` decorator for an asynchronous function. It shows how subsequent calls to the cached function with the same arguments will retrieve data from the cache rather than re-executing the heavy operation.

import asyncio import os from datetime import timedelta from cashews import cache # Configure Redis cache. Replace with your Redis URL or use "mem://" for in-memory. # For production, use environment variables for connection strings. REDIS_URL = os.environ.get("CASHEWS_REDIS_URL", "redis://localhost:6379/0") cache.setup(REDIS_URL, client_side=True) @cache(ttl=timedelta(minutes=5), key="user:{user_id}") async def get_user_data(user_id: int): """ Simulates a long-running operation to fetch user data. This function's result will be cached. """ print(f"Fetching data for user_id: {user_id} from source...") await asyncio.sleep(1) # Simulate I/O delay return {"id": user_id, "name": f"User {user_id}", "email": f"user{user_id}@example.com"} async def main(): print("First call (should fetch from source):") user1_data = await get_user_data(1) print(f"Result: {user1_data}") print("\nSecond call (should hit cache):") user1_data_cached = await get_user_data(1) print(f"Result: {user1_data_cached}") print("\nFetching data for a different user (should fetch from source):") user2_data = await get_user_data(2) print(f"Result: {user2_data}") # Example of explicit cache invalidation: # await cache.invalidate(get_user_data, user_id=1) # print("\nAfter invalidation, first call again (should fetch from source):") # user1_data_recalled = await get_user_data(1) # print(f"Result: {user1_data_recalled}") if __name__ == "__main__": asyncio.run(main())
Debug
Known issues
breakingCashews dropped support for Python 3.9 starting from version 7.5.0. Ensure your project uses Python 3.10 or newer.
fix
Upgrade your Python environment to 3.10 or higher, or pin Cashews to a version older than 7.5.0 (e.g., `cashews<7.5.0`).
affects: >=7.5.0
gotchaThe `ttl` (time-to-live) parameter is mandatory for all cache decorators and direct cache operations to prevent unbounded storage growth and ensure proper cache invalidation. Failing to provide `ttl` can lead to memory or storage overflow.
fix
Always specify `ttl` (e.g., `ttl="1h"`, `ttl=timedelta(hours=1)`) when defining a cache decorator or calling `cache.set()` and similar methods.
affects: All versions
gotchaWhen using Redis, Cashews defaults to `pickle` for serializing values. While convenient, `pickle` can have security implications with untrusted data and may not serialize all object types. It's recommended to use the `secret` and `digestmod` parameters for enhanced security, or consider other serialization options if available.
fix
Configure `cache.setup()` with `secret` and `digestmod` (e.g., `cache.setup(..., secret='your_secret_key', digestmod='sha256')`) to protect against tampering. For more complex types, consider `dill` (install `cashews[dill]`).
affects: All versions with Redis backend
gotchaUsing wildcard patterns (e.g., `"items:page:*"`) with `cache.invalidate()` when connected to a Redis backend can be inefficient. This operation might scan the entire Redis database, leading to performance issues on large datasets.
fix
Prefer using Cashews' tag system for cache invalidation, which is designed for more efficient targeted invalidation with Redis.
affects: All versions with Redis backend
gotchaIn earlier versions (prior to 7.4.4), improper cross-context usage of Cashews could lead to `ContextVar LookupError`. This typically occurs in complex asynchronous applications where contexts are not managed correctly.
fix
Upgrade Cashews to version 7.4.4 or newer to benefit from the fix. If upgrading is not possible, ensure proper ContextVar management within your asynchronous code, particularly in frameworks that heavily rely on context switching.
affects: <7.4.4
gotchaWhen utilizing Redis client-side caching with Cashews, manually modifying or expiring keys in Redis directly (e.g., via `redis-cli`) will invalidate the client-side cache for those keys, but Cashews' internal state might not immediately reflect these external changes if not managed carefully. This can lead to unexpected cache misses or stale data if not properly accounted for.
fix
Always use Cashews' API (`cache.set()`, `cache.delete()`, `cache.invalidate()`) for all cache modifications when client-side caching is enabled to ensure consistency across all layers. Avoid direct manipulation of cached keys in Redis via external tools or clients.
affects: All versions with Redis client-side caching
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'cashews'
The `cashews` package is not installed in the current Python environment, or the environment where the code is being run is not the one where `cashews` was installed.
fix
Ensure `cashews` is installed: `pip install cashews` or `pip install cashews[redis]` if using the Redis backend. If using a virtual environment, ensure it's activated before installation.
redis.exceptions.ConnectionError: No connection available.
This error typically occurs when the `cashews` Redis backend cannot establish or maintain a connection to the Redis server. This can be due to the Redis server not running, incorrect connection parameters, or issues with connection pooling and closure, especially in asynchronous contexts where connections might not be properly returned to the pool.
fix
Verify that your Redis server is running and accessible from your application. Check your Redis connection string and parameters in `cashews.setup()` or `cashews.create()` calls. Ensure that asynchronous Redis clients and connection pools are properly managed and closed when the application shuts down. You might need to configure connection pool settings if experiencing high load.
RuntimeWarning: coroutine was never awaited
This warning indicates that an asynchronous function (a coroutine), likely a cached function decorated by `cashews`, was called but the `await` keyword was omitted. Asynchronous functions must be awaited to execute their logic.
fix
Prefix the call to the asynchronous cached function with `await`. For example, if you have `@cache.memo()` on an `async def my_func()`, you must call it as `await my_func()`.
Upgrade
Version history
7.5.0latest on PyPI · released Mar 2, 2026
Audit
Dependencies
pythonrequiredRequires Python 3.10 or higher.
redisoptionalOptional, required for Redis backend functionality.
diskcacheoptionalOptional, required for DiskCache backend functionality.
dilloptionalOptional, for enhanced serialization of more object types in Redis.
xxhashoptionalOptional, for improved hashing algorithms (e.g., in Bloom filters or digestmod).
bitarrayoptionalOptional, for speedup with Bloom filters.
hiredisoptionalOptional, for faster Redis parsing.
Agent activity
44 hits · last 30 days
node
38
Amazon
1
OpenAI (training)
1
Resources
cashews — pip install cashews · libregistry