A simple package to add timeout to requests
Project description
Timeout Decorator
A versatile timeout decorator for both synchronous and asynchronous functions in Python.
Features
- Works with both synchronous and asynchronous functions
- Customizable timeout duration
- Optional callback function on timeout
- Support for custom exception on timeout
- Colored logging
Installation
pip install timeout-decorator
Parameters
timeout: The maximum execution time in seconds.
callback (optional): A function to be called if the timeout occurs.
custom_error (optional): A custom exception class to be raised on timeout.
Usage
Basic Usage
from timeout_decorator import timeout_decorator
@timeout_decorator(5) # 5 seconds timeout
def my_function():
# Your code here
pass
@timeout_decorator(10) # 10 seconds timeout
async def my_async_function():
# Your async code here
pass
Advanced Usage
from timeout_decorator import timeout_decorator
def on_timeout(func_name, *args, **kwargs):
print(f"Function {func_name} timed out!")
class MyTimeoutError(Exception):
pass
@timeout_decorator(5, callback=on_timeout, custom_error=MyTimeoutError)
def my_function():
# Your code here
pass
# Usage with synchronous function
try:
result = my_function()
except MyTimeoutError:
print("Caught custom timeout error")
# Usage with asynchronous function
@timeout_decorator(5, callback=on_timeout, custom_error=MyTimeoutError)
async def my_async_function():
# Your async code here
pass
import asyncio
async def main():
try:
result = await my_async_function()
except MyTimeoutError:
print("Caught custom timeout error")
asyncio.run(main())
Tests
run
pytest tests/test_timeout_decorator.py -v
Notes
For synchronous functions, the decorator uses a ThreadPoolExecutor to implement the timeout.
For asynchronous functions, it uses asyncio.wait_for().
The decorator automatically detects whether the decorated function is synchronous or asynchronous.
Licence
This project is licensed under the MIT License
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file python_timeout_request_himanshu007_creator-0.0.1-py3-none-any.whl.
File metadata
- Download URL: python_timeout_request_himanshu007_creator-0.0.1-py3-none-any.whl
- Upload date:
- Size: 3.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.10.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ce60a66d5152e9caecbf9095600f21110be864f479b811142ae1094c93d9724e
|
|
| MD5 |
a903752bdd9980f90a7a8bf4620577d9
|
|
| BLAKE2b-256 |
1f47858bfc1c600c982dd8b0f0c3754f672d3ee853e9ea4292c713b7892f24ff
|