The `timeout-decorator` library provides a simple Python decorator to enforce execution time limits on functions. It primarily uses Unix signals for timeouts in the main thread but offers a multiprocessing strategy for use in other threads or on Windows. The library is currently at version 0.5.0, with its last release in 2020, but it remains a commonly used solution for function timeouts.
pip install timeout-decoratorVerified import paths — ran on the pinned version, not inferred.
This example demonstrates basic usage with both the default signal-based timeout and the multiprocessing strategy. The `long_running_function` will time out after 5 seconds using signals, while `another_long_running_function` will time out after 3 seconds using the multiprocessing approach, useful for non-main threads or Windows.
Use `@timeout(seconds, use_signals=False)` when decorating functions in non-main threads or on Windows.
Ensure all inputs and outputs of the timed-out function are compatible with Python's `pickle` module. Avoid complex objects or closures that cannot be serialized.
For nested timeouts, set `use_signals=False` for all inner decorators. The outermost decorator can optionally use signals if it's in the main thread.
Refine exception handling within timed-out functions to catch specific exceptions rather than broad `Exception` clauses, or ensure `TimeoutError` is re-raised.
While no official fix is provided within `timeout-decorator` v0.5.0, consider using alternative, more actively maintained timeout libraries (e.g., `wrapt-timeout-decorator`) for newer Python versions if issues arise.
pip install timeout-decorator
Apply the decorator with `use_signals=False` and `use_multiprocessing=True` (or `use_thread=True` for simpler thread-based scenarios without multiprocessing overhead).
```python
import timeout_decorator
import time
@timeout_decorator.timeout(5, use_signals=False, use_multiprocessing=True)
def my_function():
time.sleep(10)
return "Done"
try:
my_function()
except timeout_decorator.TimeoutError:
print("Function timed out!")
```Add parentheses to the decorator call, passing the timeout duration as the first argument.
```python
import timeout_decorator
import time
@timeout_decorator.timeout(1)
def my_function():
time.sleep(2)
return "Done"
try:
my_function()
except timeout_decorator.TimeoutError:
print("Function timed out!")
```Explicitly import and catch `timeout_decorator.TimeoutError`.
```python
import timeout_decorator
import time
@timeout_decorator.timeout(1)
def long_running_function():
time.sleep(2)
return "Completed"
try:
long_running_function()
except timeout_decorator.TimeoutError: # Correctly catches the library's specific exception
print("Function timed out as expected!")
```No dependency data recorded yet.