Wrapt Timeout Decorator

1.5.1 · active · verified Sun Apr 12

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.

Warnings

Install

Imports

Quickstart

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.

import time
from wrapt_timeout_decorator import timeout, TimeoutError

@timeout(5)
def long_running_function():
    print("Starting long_running_function...")
    for i in range(1, 10):
        time.sleep(1)
        print(f'{i} seconds passed inside function.')
    print("long_running_function finished.")

if __name__ == '__main__':
    try:
        long_running_function()
        print("Function completed without timeout.")
    except TimeoutError:
        print("Function timed out after 5 seconds.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

view raw JSON →