A real-world example of using the timeout() decorator in Python could be when dealing with network operations that may block indefinitely or for a long time. In such situations, it's useful to have a timeout feature that ensures that the operation is aborted after a certain amount of time has elapsed.
Here's an example of a timeout() decorator that can be used to limit the execution time of a function:
import signalclass TimeoutException(Exception): passdef timeout(seconds=10): def decorator(func): def wrapper(*args, **kwargs): def handler(signum, frame): raise TimeoutException("Function timed out") signal.signal(signal.SIGALRM, handler) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wrapper return decorator |
In this example, the timeout() decorator takes an integer number of seconds as an argument and returns a decorator that can be applied to any function. The returned decorator wraps the original function with code that sets a signal alarm that interrupts the function after the specified number of seconds has elapsed.
Here's an example of how to use this decorator to limit the execution time of a function to 5 seconds:
@timeout(5)def slow_function(): import time time.sleep(10)try: slow_function()except TimeoutException: print("Function timed out") |
Output:
Function timed out |
In this example, the slow_function() function is decorated with the timeout() decorator with a limit of 5 seconds. When the function is called, it will sleep for 10 seconds, which should trigger the timeout exception. The try and except block handles the exception and prints a message.
Note that the timeout() decorator can be applied to any function that takes any number of arguments, and it can be used in any situation where it's necessary to limit the execution time of a function. It's a useful tool for adding robustness to Python code that deals with network operations, file I/O, or any other potentially long-running task.