Add a timeout to any function call, sync or async.
pip install philiprehberger-func-timeoutAdd a timeout to any function call, sync or async.
pip install philiprehberger-func-timeout
from philiprehberger_func_timeout import timeout
import time
@timeout(2.0)
def slow_computation() -> str:
time.sleep(10)
return "done"
slow_computation() # raises TimeoutError after 2 seconds
@timeout(1.5)
async def fetch_data(url: str) -> str:
await asyncio.sleep(10)
return "data"
await fetch_data("https://example.com") # raises TimeoutError after 1.5s
@timeout(2.0, fallback="default")
def risky_call() -> str:
time.sleep(10)
return "result"
risky_call() # returns "default" instead of raising
class MyError(Exception):
def __init__(self, seconds: float) -> None:
super().__init__(f"Took too long: {seconds}s")
@timeout(3.0, exception=MyError)
def slow() -> None:
time.sleep(10)
from philiprehberger_func_timeout import retry
@retry(attempts=3, delay=1.0, backoff=2.0)
def fetch_data(url: str) -> str:
return requests.get(url).text
result = fetch_data("https://api.example.com/data")
| Function / Class | Description |
|---|---|
timeout(seconds, *, fallback, exception) | Decorator that adds a timeout to sync or async functions |
TimeoutError | Raised on timeout; has a .seconds attribute |
timeout_context(seconds, *, fallback, exception) | Context manager that raises on timeout |
retry(attempts, delay, *, backoff, on_error) | Decorator that retries a function on failure with optional backoff |
pip install -e .
python -m pytest tests/ -v
If you find this project useful: