stouputils.decorators.timeout module#
- timeout(
- func: Callable[..., T],
- *,
- seconds: float = 60.0,
- message: str = '',
- timeout(
- func: None = None,
- *,
- seconds: float = 60.0,
- message: str = '',
Decorator that raises a TimeoutError if the function runs longer than the specified timeout.
Note: This decorator uses SIGALRM on Unix systems, which only works in the main thread. On Windows or in non-main threads, it will fall back to a polling-based approach.
- Parameters:
func (Callable[..., T] | None) – Function to apply timeout to
seconds (float) – Timeout duration in seconds (default: 60.0)
message (str) – Custom timeout message (default: “Function ‘{func_name}’ timed out after {seconds} seconds”)
- Raises:
TimeoutError – If the function execution exceeds the timeout duration
Examples
>>> import time >>> @timeout(seconds=2.0) ... def slow_function(): ... time.sleep(5) >>> slow_function() # Raises TimeoutError after 2 seconds Traceback (most recent call last): ... TimeoutError: Function 'slow_function()' timed out after 2.0 seconds
>>> @timeout(seconds=1.0, message="Custom timeout message") ... def another_slow_function(): ... time.sleep(3) >>> another_slow_function() # Raises TimeoutError after 1 second Traceback (most recent call last): ... TimeoutError: Custom timeout message