- Python 100%
Adds CacheStats dataclass with num_entries and size_bytes fields. FilesystemResultStore.get_stats() counts .pkl files (one per cached entry) and sums the sizes of all files in the store directory. Also adds test_get_stats() to verify empty and populated store stats. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> |
||
|---|---|---|
| src/watt42_cached | ||
| tests | ||
| .gitignore | ||
| .python-version | ||
| pyproject.toml | ||
| README.md | ||
| uv.lock | ||
Watt42 - Caching Library
This tiny package implements file-based caching of async function results. It is designed to be used within Watt42 scripts, but can also be used outside of Watt42.
Please note: Caching is powerful, and works "like magic". However, if you use it in an inadequate way, it can lead to frustration. Make sure you apply caching responsibly.
Good examples when to use caching are:
- When you have a function that takes a long time to compute and is called multiple times with the same parameters.
- When fetching data from a remote API, and this data does not change once fetched, e.g. inverter history data, weather data, etc.
- etc.
Features
- File-based caching of async function results
- Automatic cache key generation based on function name and parameters
- Cache context management for use within Watt42 scripts or outside of Watt42
- Cache size management with low and high watermarks
Installation
If you use it from within a Watt42 script, no installation is necessary. I you
use it outside, install with pip or uv:
pip install watt42-cached
Usage
from watt42_cached import cached
@cached
async def get_data(key: str):
# Simulate a long-running operation
await asyncio.sleep(2)
return {"data": "This is cached data for key: " + key}
This will cache the result of get_data based on the function name and its
parameters. The next time you call get_data with the same key, it will return
the cached result instead of executing the function again.
For this to work, the cache context needs to be defined. When using @cached
within a Watt42 script, the context is automatically set up. If you use it
outside of Watt42, you need to set up the cache context manually:
from watt42_cached import FileSystemResultStore, CacheContext, cache_context
cachedir = "/path/to/cache/directory"
store = FilesystemResultStore(cachedir, lwm_pct=0.8, hwm_pct=0.9)
token = cache_context.set(CacheContext(cache_key="my-cache-key", store=store))
... and once done, you can reset the context:
cache_context.reset(token)
Development
Prerequisites
- Python 3.11 or higher
uv(https://docs.astral.sh/uv/getting-started/installation/)
Run Tests
Run all tests, with coverage report:
uv run pytest --cov=src --cov-report=term-missing