Metadata-Version: 2.3
Name: watt42-cached
Version: 0.1.0
Summary: Watt42 Caching Library
Author: Chris Oloff
Author-email: Chris Oloff <chris@uber5.com>
Requires-Dist: tenacity>=9.1.4
Requires-Python: >=3.11
Description-Content-Type: text/markdown

# 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`:

```bash
pip install watt42-cached
```

## Usage

```python
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:

```python
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:

```python
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:

```bash
uv run pytest --cov=src --cov-report=term-missing
```
