Skip to main content

Add a timeout to any function call — sync or async

Project description

philiprehberger-func-timeout

Tests PyPI version License

Add a timeout to any function call — sync or async.

Install

pip install philiprehberger-func-timeout

Usage

from philiprehberger_func_timeout import timeout

Sync functions

import time

@timeout(2.0)
def slow_computation() -> str:
    time.sleep(10)
    return "done"

slow_computation()  # raises TimeoutError after 2 seconds

Async functions

@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

Fallback value

@timeout(2.0, fallback="default")
def risky_call() -> str:
    time.sleep(10)
    return "result"

risky_call()  # returns "default" instead of raising

Custom exception

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)

API

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

Development

pip install -e .
python -m pytest tests/ -v

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

philiprehberger_func_timeout-0.1.4.tar.gz (3.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

philiprehberger_func_timeout-0.1.4-py3-none-any.whl (4.3 kB view details)

Uploaded Python 3

File details

Details for the file philiprehberger_func_timeout-0.1.4.tar.gz.

File metadata

File hashes

Hashes for philiprehberger_func_timeout-0.1.4.tar.gz
Algorithm Hash digest
SHA256 6deacb5fe16c0ecd25dfd02c52f4a8ea56f0b1172688c3081bcd150c5d6bccb6
MD5 ea7022e125f61392f08494d4893999e9
BLAKE2b-256 434a738e8aa2e270ebf2915ac42c397b8025d4a61007ef8b4442aa053774aa93

See more details on using hashes here.

File details

Details for the file philiprehberger_func_timeout-0.1.4-py3-none-any.whl.

File metadata

File hashes

Hashes for philiprehberger_func_timeout-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 3f36559d90ee47ea5ff5652035d55dfd46e4a9d0fe44bef6c6d70a62787f0aa7
MD5 2a801c739d35c7a8554564770f7a32c8
BLAKE2b-256 25cf2081d37e3488e539e92be5a8dc103628e2affa27a2e6a0d7c80bf4375141

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page