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

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.2.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.2-py3-none-any.whl (4.3 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for philiprehberger_func_timeout-0.1.2.tar.gz
Algorithm Hash digest
SHA256 87191d37fa8af7c99b3981741f7e7e7f97766a4c2a8068eccbc36fd9c18d16bb
MD5 f540680b4903c193df25701e7bcf8399
BLAKE2b-256 41f40d1f84283461d8f6f42c227a5567fc7718a43252db7e2a8cb187d494e40b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for philiprehberger_func_timeout-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 e4cdedd802a28e480845080fce82ecd4f2ec99082502363ba280a4e430662a2d
MD5 35339c2581cf9a4b716c461f0aa23e45
BLAKE2b-256 012670a4272842933a221caa4deadd03099e912c1f539a828952998f3d57e96b

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