Registry / testing / timeout-decorator

timeout-decorator

JSON →
library0.5.0pypypi✓ verified 26d ago

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-decorator
INSTALL
IMPORT
SIG · TIMEOUT-DECORATOR
T
timeout-decorator
testingpythonv0.5.0
Install
2.4s avg
Import
42ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.5.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.044s · 19.2MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.4s · import 0.040s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

timeout
from timeout_decorator import timeout
The primary decorator for applying timeouts.

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.

import time import timeout_decorator @timeout_decorator.timeout(5) def long_running_function(): print("Starting long_running_function...") for i in range(1, 10): time.sleep(1) print(f"{i} seconds have passed inside function") print("long_running_function completed.") @timeout_decorator.timeout(3, use_signals=False) def another_long_running_function(): print("Starting another_long_running_function with multiprocessing strategy...") for i in range(1, 10): time.sleep(1) print(f"{i} seconds have passed inside function") print("another_long_running_function completed.") if __name__ == '__main__': print("--- Testing signal-based timeout ---") try: long_running_function() except timeout_decorator.TimeoutError: print("long_running_function timed out after 5 seconds.") print("\n--- Testing multiprocessing-based timeout ---") try: another_long_running_function() except timeout_decorator.TimeoutError: print("another_long_running_function timed out after 3 seconds.")
Debug
Known issues
gotchaThe default signal-based timeout strategy (when `use_signals=True` or omitted) only works in the main thread on Unix-like operating systems. It is not compatible with Windows or functions running in non-main threads. For these cases, you must explicitly pass `use_signals=False` to switch to a multiprocessing-based strategy.
fix
Use `@timeout(seconds, use_signals=False)` when decorating functions in non-main threads or on Windows.
affects: <=0.5.0
gotchaWhen using the multiprocessing strategy (`use_signals=False`), all arguments passed to the decorated function and any values returned by it must be picklable. If they are not, the function call will fail with a `PicklingError`.
fix
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.
affects: <=0.5.0
gotchaSignal-based timeouts do not support nesting. If an outer function and an inner function are both decorated with `timeout` using signals, the inner timeout will cancel and override the outer one. Only one `SIGALRM` can be active per process.
fix
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.
affects: <=0.5.0
gotchaFunctions decorated with `@timeout` can inadvertently suppress `TimeoutError` if they broadly catch exceptions (e.g., `except Exception:`). This can prevent the timeout mechanism from effectively terminating the function or raising the expected error.
fix
Refine exception handling within timed-out functions to catch specific exceptions rather than broad `Exception` clauses, or ensure `TimeoutError` is re-raised.
affects: <=0.5.0
gotchaSome users have reported compatibility issues with `timeout-decorator` on Python 3.8 and newer versions, specifically related to changes in internal function naming, which could lead to `AttributeError` or unexpected behavior.
fix
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.
affects: >=3.8
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'timeout_decorator'
The `timeout-decorator` library has not been installed in the current Python environment.
fix
pip install timeout-decorator
UserWarning: Cannot use SIGALRM signal, use multiprocessing timeout strategy
The default signal-based timeout mechanism (`signal.SIGALRM`) is not supported on the current operating system (e.g., Windows) or when the decorated function is executed in a non-main thread.
fix
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!")
```
TypeError: timeout() missing 1 required positional argument: 'timeout_duration'
The `@timeout_decorator.timeout` decorator was applied without parentheses, meaning it was treated as a function object rather than being called with the required timeout duration argument.
fix
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!")
```
timeout_decorator.TimeoutError: Function timed out after X seconds (traceback when `except TimeoutError` is used)
The code attempts to catch Python's built-in `TimeoutError` (or one from another library like `concurrent.futures`) instead of the specific `timeout_decorator.TimeoutError` exception raised by this library.
fix
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!")
```
Upgrade
Version history
0.5.0latest on PyPI · released Nov 15, 2020
Audit
Dependencies

No dependency data recorded yet.

Agent activity
13 hits · last 30 days
node
10
Resources
timeout-decorator — pip install timeout-decorator · libregistry