wrapt-timeout-decorator is a Python library providing a robust timeout decorator. It emphasizes correctness when used with various types of methods (e.g., class, static) and preserves traceback information for debugging. It supports dynamic timeout adjustment and offers two strategies: 'Signals' (for POSIX systems and main thread) and 'Subprocess' (the default, compatible with Windows and multithreaded environments, utilizing `multiprocess` and `dill` for extended pickling capabilities). The library is actively maintained, with version 1.5.1 released in February 2024.
pip install wrapt-timeout-decoratorVerified import paths — ran on the pinned version, not inferred.
This example demonstrates applying the `@timeout` decorator to a function. The function `long_running_function` is designed to run for 9 seconds. However, with a timeout set to 5 seconds, a `TimeoutError` will be raised, and the `except` block will catch it, indicating the function timed out.
Move decorated functions into a separate Python module (e.g., `my_module.py`) and import them into your main script. This ensures they are properly picklable for subprocess execution.
For cross-platform compatibility or use in subthreads, rely on the default 'Subprocess' strategy (`use_signals=False` or omit the parameter). Explicitly set `use_signals=True` only when targeting POSIX main threads.
Avoid setting `allow_eval=True` unless strictly necessary and ensure that any string passed for evaluation (`dec_timeout`) originates from a trusted, controlled source.
When `dec_hard_timeout=True` is used, ensure the timeout value is sufficiently long to account for process spawning overhead. For very short timeouts, consider if `dec_hard_timeout` is truly necessary or if a slightly more flexible timeout is acceptable.
For nested timeouts, ensure that `use_signals=True` is applied only to the outermost `@timeout` decorator. All inner decorators must explicitly or implicitly use `use_signals=False`.