Registry / database / asyncache

asyncache

JSON →
library0.3.1pypypi✓ verified 23d ago

asyncache is a Python library providing helpers to easily integrate `cachetools` caching strategies with asynchronous Python code, specifically designed for `asyncio` applications. It allows developers to decorate `async` functions to transparently cache their results. The current version is 0.3.1, released in November 2022, and it appears to be actively maintained through issues and pull requests, though new releases are infrequent.

pip install asyncache
INSTALL
IMPORT
SIG · ASYNCACHE
A
asyncache
databasepythonv0.3.1
Install
1.9s avg
Import
212ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.3.1 · 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.95 runs
installs and imports cleanly · install 0.0s · import 0.222s · 17.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.9s · import 0.202s · 18MB
16MB installed
● package 16MB
Code
Verified usage

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

cached
from asyncache import cached
TTLCache
from cachetools import TTLCache
cachetools provides the actual caching implementations.

This quickstart demonstrates how to use the `@cached` decorator from `asyncache` with a `TTLCache` from `cachetools` to cache the results of an asynchronous function. It shows cache hits and misses, and how Time-To-Live (TTL) expiration works.

import asyncio from asyncache import cached from cachetools import TTLCache # A simple async function that simulates an expensive operation async def fetch_user_data(user_id: int) -> dict: print(f"Fetching data for user {user_id} from database...") await asyncio.sleep(1) # Simulate I/O delay return {"id": user_id, "name": f"User {user_id} Name"} # Cache the results of the async function using TTLCache from cachetools # The cache will hold up to 1024 items, with each entry expiring after 60 seconds. @cached(TTLCache(maxsize=1024, ttl=60)) async def get_user_cached(user_id: int) -> dict: return await fetch_user_data(user_id) async def main(): print("--- First call (cache miss) ---") user1 = await get_user_cached(1) print(f"Result: {user1}\n") print("--- Second call (cache hit) ---") user1_cached = await get_user_cached(1) print(f"Result: {user1_cached}\n") print("--- Third call with different ID (cache miss) ---") user2 = await get_user_cached(2) print(f"Result: {user2}\n") print("--- Waiting for TTL to expire (will force a re-fetch) ---") await asyncio.sleep(61) # Wait for cache entry to expire print("--- Fourth call (cache miss after TTL) ---") user1_after_ttl = await get_user_cached(1) print(f"Result: {user1_after_ttl}\n") if __name__ == "__main__": asyncio.run(main())
Debug
Known issues
gotchaCareful selection and configuration of the underlying `cachetools` policy (e.g., `TTLCache`, `LRUCache`) is crucial. A poorly chosen or configured policy can lead to low cache hit rates, stale data, or excessive memory usage. For instance, ensure `maxsize` and `ttl` parameters are appropriate for your application's needs.
fix
Thoroughly understand `cachetools` policies. Monitor cache hit/miss rates in production to validate your chosen policy and parameters. Adjust `maxsize` and `ttl` as needed, considering memory constraints and data freshness requirements.
affects: All versions
gotchaCache invalidation remains a hard problem. While `asyncache` handles the caching mechanism, manual invalidation or ensuring data consistency across multiple cache instances or sources is still the developer's responsibility. Stale data can be served if the cache entry's TTL is too long or if the underlying data changes without cache awareness.
fix
Implement explicit cache invalidation mechanisms (e.g., `cache.clear()`, `del cache[key]`) when source data changes. Consider a 'write-through' or 'write-behind' caching strategy if applicable, or adopt a shorter TTL for highly dynamic data. Use unique, deterministic cache keys.
affects: All versions
gotchaUsing decorators like `@cached` can sometimes interfere with static analysis, introspection, or type checkers (e.g., Pyright) when dealing with class method inheritance, potentially leading to errors or requiring `# type: ignore` comments. The decorator wraps the original function, changing its runtime characteristics.
fix
If encountering issues with type checkers or introspection, consider adding `# type: ignore` comments to suppress false positives. Alternatively, evaluate if caching can be applied at a service layer function rather than directly on inherited class methods, or explore explicit caching logic within the method body.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'asyncache'
The 'asyncache' package is not installed in the Python environment.
fix
Install the package using pip: 'pip install asyncache'.
ImportError: cannot import name 'cached' from 'asyncache'
The 'cached' decorator is not available in the 'asyncache' module, possibly due to an outdated version.
fix
Ensure you have the latest version of 'asyncache' installed: 'pip install --upgrade asyncache'.
TypeError: 'cached' object is not callable
The 'cached' decorator is being used incorrectly, likely applied to a non-async function.
fix
Ensure that the function decorated with 'cached' is defined as 'async def'.
AttributeError: module 'asyncache' has no attribute 'cached'
The 'cached' decorator is not found in the 'asyncache' module, possibly due to an incorrect import or outdated version.
fix
Verify the import statement: 'from asyncache import cached' and ensure 'asyncache' is up to date.
TypeError: 'TTLCache' object is not callable
The 'TTLCache' from 'cachetools' is being used incorrectly, possibly instantiated without parentheses.
fix
Instantiate 'TTLCache' correctly: 'cache = TTLCache(maxsize=1024, ttl=60)'.
Upgrade
Version history
0.3.1latest on PyPI · released Nov 15, 2022
Audit
Dependencies
cachetoolsrequiredasyncache provides an asynchronous wrapper around cachetools' caching strategies.
Agent activity
21 hits · last 30 days
node
18
Amazon
1
OpenAI (training)
1
Resources
asyncache — pip install asyncache · libregistry