func-timeout

4.3.6 · active · verified Sat Apr 11

`func-timeout` is a Python module that enables setting timeouts for arbitrary function calls, preventing them from running indefinitely. It achieves this by executing the function in a separate thread and forcefully terminating it if the specified duration is exceeded. The latest version is 4.3.6, with a historically sporadic release cadence, recently updated to support newer Python versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use both the `func_timeout` function and the `func_set_timeout` decorator to apply timeouts to Python functions. It shows how `FunctionTimedOut` is raised when the timeout is exceeded.

import time
from func_timeout import func_timeout, FunctionTimedOut, func_set_timeout

def long_running_function(duration):
    print(f"Starting long_running_function for {duration} seconds...")
    time.sleep(duration)
    print("long_running_function completed.")
    return "Done"

# Example 1: Using func_timeout for a direct call
try:
    print("\n--- Using func_timeout ---")
    result = func_timeout(1, long_running_function, args=(5,))
    print(f"Result: {result}")
except FunctionTimedOut:
    print("Function timed out after 1 second!")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

# Example 2: Using func_set_timeout decorator
@func_set_timeout(1)
def decorated_function(duration):
    print(f"Starting decorated_function for {duration} seconds...")
    time.sleep(duration)
    print("decorated_function completed.")
    return "Decorated Done"

try:
    print("\n--- Using func_set_timeout decorator ---")
    result = decorated_function(5)
    print(f"Result from decorator: {result}")
except FunctionTimedOut:
    print("Decorated function timed out after 1 second!")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →