Metadata-Version: 2.5
Name: opero
Version: 2.7.8
Summary: Resilient, parallel task orchestration for Python
Project-URL: Documentation, https://github.com/twardoch/opero#readme
Project-URL: Issues, https://github.com/twardoch/opero/issues
Project-URL: Source, https://github.com/twardoch/opero
Author-email: Adam Twardoch <adam@twardoch.com>
License: MIT License
        
        Copyright (c) 2023 Adam Twardoch
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: concurrency,fallback,orchestration,parallel,rate-limiting,resilience,retry
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Requires-Python: >=3.10
Requires-Dist: asynciolimiter>=1.0.0
Requires-Dist: klepto>=0.2.7
Requires-Dist: tenacity>=8.0.0
Requires-Dist: twat-cache>=2.3.0
Requires-Dist: twat-mp>=2.6.0
Provides-Extra: aiomultiprocess
Requires-Dist: aiomultiprocess>=0.9.0; extra == 'aiomultiprocess'
Provides-Extra: all
Requires-Dist: aiomultiprocess>=0.9.0; extra == 'all'
Requires-Dist: pathos>=0.3.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: black>=23.1.0; extra == 'dev'
Requires-Dist: mypy>=1.0.0; extra == 'dev'
Requires-Dist: pre-commit>=3.6.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: pathos
Requires-Dist: pathos>=0.3.0; extra == 'pathos'
Provides-Extra: test
Requires-Dist: klepto>=0.2.4; extra == 'test'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'test'
Requires-Dist: pytest-benchmark[histogram]>=4.0.0; extra == 'test'
Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
Requires-Dist: pytest-xdist>=3.5.0; extra == 'test'
Requires-Dist: pytest>=7.0.0; extra == 'test'
Description-Content-Type: text/markdown

# Opero: resilience and parallelism for Python functions

[![PyPI version](https://img.shields.io/pypi/v/opero.svg)](https://pypi.org/project/opero/)
[![Python versions](https://img.shields.io/pypi/pyversions/opero.svg)](https://pypi.org/project/opero/)
[![License](https://img.shields.io/github/license/twardoch/opero.svg)](https://github.com/twardoch/opero/blob/main/LICENSE)

Two decorators — `@opero` and `@opmap` — add automatic retries, parameter fallbacks, caching, rate limiting, and parallel execution to any Python function with minimal code changes.

## Install

```bash
pip install opero

# Optional extras
pip install opero[pathos]        # multiprocessing with complex objects
pip install opero[aiomultiprocess]  # async multiprocessing
pip install opero[all]           # everything
```

## Quick example

```python
from opero import opero, opmap, AllFailedError


# Single-call resilience: cache results, retry up to 3 times,
# fall back through a list of API keys on failure.
@opero(cache=True, cache_ttl=3600, retries=3, arg_fallback="api_key", rate_limit=5.0)
async def fetch(item_id: str, api_key: str = None):
    # api_key receives one value from the caller-supplied list on each attempt
    return await call_api(item_id, api_key)


# Pass the list explicitly; the decorator tries each key until one succeeds.
result = await fetch("item-123", api_key=["key1", "key2", "key3"])


# Batch resilience: same protections, applied in parallel across many items.
@opmap(mode="thread", workers=8, retries=2)
def process(item: dict):
    return transform(item)


results = process(list_of_items)  # returns list; failed items are exceptions
```

## What each mechanism does

### Retries (`retries`, `backoff_factor`, `min_delay`, `max_delay`, `retry_on`)

Re-runs the function on failure using exponential backoff with jitter (via `tenacity`). Set `retry_on` to restrict which exception types trigger a retry.

### Parameter fallbacks (`arg_fallback`)

Names a parameter that receives one value at a time from a caller-supplied list. Pass the list explicitly at call time; on each failure the decorator retries with the next item. Useful for rotating API keys, backup endpoints, or config profiles. Raises `AllFailedError` when the list is exhausted.

### Caching (`cache`, `cache_ttl`, `cache_backend`, `cache_namespace`, `cache_key`)

Skips the function body on repeated calls with the same arguments (via `twat-cache`). Backends: `"memory"` (default), `"disk"`, `"redis"`.

### Rate limiting (`rate_limit`)

Caps calls-per-second using `asynciolimiter`. Protects downstream APIs from being hammered.

### Parallel execution (`mode`, `workers`, `ordered`, `progress`) — `@opmap` only

Maps the decorated function across a list of inputs using `twat-mp`. Modes:

| Mode | Best for |
|------|---------|
| `"thread"` | I/O-bound work (HTTP, DB, file) |
| `"process"` | CPU-bound work |
| `"async"` | Async I/O functions |
| `"async_process"` | Async functions in separate processes |

Failed items are returned as exception objects in the results list rather than stopping the batch.

## Execution order

Each call goes through: **cache check → rate limiter → retry loop → fallback cycle**.

## Error handling

```python
from opero import AllFailedError

try:
    result = await fetch("item-42")
except AllFailedError as e:
    for i, err in enumerate(e.errors):
        print(f"attempt {i + 1}: {err}")
```

## Async support

Both sync and async functions work. Opero detects async functions automatically and uses async-compatible retry and rate-limit implementations.

## Logging

```python
from opero import configure_logging
import logging

configure_logging(level=logging.DEBUG)  # see retries, cache hits, fallbacks
```

## Package structure

| Module | Purpose |
|--------|---------|
| `decorators/opero.py` | `@opero` — single-call resilience decorator |
| `decorators/opmap.py` | `@opmap` — batch parallel resilience decorator |
| `core/retry.py` | Exponential backoff retry via `tenacity` |
| `core/fallback.py` | Parameter-list fallback cycling |
| `core/cache.py` | Cache integration via `twat-cache` |
| `core/rate_limit.py` | Rate limiting via `asynciolimiter` |
| `concurrency/pool.py` | Parallel executor via `twat-mp` |
| `exceptions.py` | `OperoError`, `AllFailedError` |

## Development

```bash
git clone https://github.com/twardoch/opero && cd opero
pip install hatch
hatch shell
hatch run test          # run tests
hatch run lint:all      # ruff + mypy
```

## License

MIT.
