Version v1.5.1 as of 2024-02-28 see Changelog
There are several timeout decorators available, but the one mentioned here focuses on ensuring correctness when used with classes, methods, class methods, static methods, etc. It also preserves traceback information for PyCharm debugging.
The timeout can be dynamically adjusted, calculated from other parameters or methods accessible via an optional eval function.
Two timeout strategies have been implemented: one using "Signals" and the other using "Subprocess".
The "Signals" strategy (for POSIX Systems) is elegant and efficient, but it has some important caveats which should be reviewed in the Considerations using Signals section.
The utilization of subprocesses serves as the default approach for executing timeouts:
- Windows Compatibility:
- Given the absence of signal support,
subprocesses become the sole method for implementing timeouts on Windows,
automatically applied to accommodate the platform's limitations.
On Windows the only available startmethod for subprocesses is
spawn
- POSIX Systems:
- On POSIX-compliant systems, signals cannot be employed within
subthreads, necessitating the use of subprocesses in these contexts as well.
On POSIX the available startmethods for subprocesses are
fork,forkserver,spawn
To ensure compatibility and functionality across subprocesses,
it's essential that as many object types as possible are pickleable.
To this end, the dill library is preferred over Python's standard pickle module,
and multiprocess is chosen instead of multiprocessing.
dill enhances the pickle module's capabilities, extending support for
serialization and deserialization of a broader array of Python object types.
Subprocess communication is facilitated through multiprocess.pipe rather than queue.
This choice not only boosts performance but also enhances compatibility,
potentially offering better support for environments like Amazon AWS.
Subprocesses can be initiated using various methods, including 'fork', 'forkserver', and 'spawn'. For detailed information on these methods and their implications, please refer to Section Considerations using Subprocesses of this manual.
automated tests, Github Actions, Documentation, Badges, etc. are managed with PizzaCutter (cookiecutter on steroids)
Python version required: 3.8.0 or newer
tested on recent linux with python 3.8, 3.9, 3.10, 3.11, 3.12, pypy-3.9, pypy-3.10 - architectures: amd64
100% code coverage, flake8 style checking ,mypy static type checking ,tested under Linux, macOS, Windows, automatic daily builds and monitoring
- Try it Online
- Usage
- Usage from Commandline
- Installation and Upgrade
- Requirements
- Acknowledgements
- Contribute
- Report Issues
- Pull Request
- Code of Conduct
- License
- Changelog
You might try it right away in Jupyter Notebook by using the "launch binder" badge, or click here
- Basic Usage
- General Recommendations
- Considerations using Signals
- Handling Nested Timeouts
- Custom Timeout Exception
- Parameters
- Override Parameters
- Multithreading
- Subprocess Monitoring
- use as function not as decorator
- Dynamic Timeout Value Adjustment with eval
- Logging Challenges with Subprocesses
- hard timeout
- Understanding Timeout Durations Across Platforms
- MYPY Testing
import time
from wrapt_timeout_decorator import *
@timeout(5)
def mytest(message):
# this example does NOT work on windows, please check the section
# "use with Windows" in the README.rst
print(message)
for i in range(1,10):
time.sleep(1)
print('{} seconds have passed'.format(i))
if __name__ == '__main__':
mytest('starting')It's recommended to minimize the utilization of timeouts in your programming, reserving them for truly essential instances.
Timers should be applied at an appropriate level of detail, tailored specifically to the needs of your application. This precision aids in circumventing unwanted outcomes, such as the mishandling of exceptions by unrelated code sections or complications with entities that cannot be pickled.
Conversely, it's prudent to refrain from embedding a Timeout Decorator within loops that execute multiple times. Such an approach can induce notable delays, especially on Windows systems, owing to the additional burden of initiating subprocesses.
Where possible, opt for the timeout features natively available in the functions and libraries at your disposal. These inherent capabilities are often adequate for the majority of use cases. The implementation of a Timeout Decorator is best reserved as a measure of last resort, subsequent to the exhaustive consideration of alternative strategies.
Additionally, be cognizant of the fact that the behavior and efficiency of subprocesses may vary significantly across platforms (Windows versus Linux) and depending on the chosen method for subprocess initiation. Refer to the documentation on Subprocess Start Methods for further details.
BAD EXAMPLE (Pseudocode) - lets assume the write to the database fails sometimes for unknown reasons, and "hangs"
# module file_analyzer import time from wrapt_timeout_decorator import * def read_the_file(filename): ... def analyze_the_file(filename): ... def write_to_database(file_content): ... @timeout(5) # try to minimize the scope of the timeout def import_file(filename): file_content = read_the_file(filename) structured_data = analyze_the_file(file_content) write_to_database(structured_data)BETTER EXAMPLE (Pseudocode)
# module file_analyzer import time from wrapt_timeout_decorator import * def read_the_file(filename): ... def analyze_the_file(filename): ... @timeout(5) # better, because smaller scope def write_to_database(file_content): ... def import_file(filename): file_content = read_the_file(filename) structured_data = analyze_the_file(file_content) write_to_database(structured_data)
To bypass complexities, simply place the decorated function within a separate module, rather than in the main script.
On Windows, due to the absence of native forking support, Python attempts to emulate a forking environment. This emulation involves re-importing the main module under a different name, not as '__main__'. This behavior is part of Python's multiprocessing efforts to replicate the main process's environment as closely as possible. Consequently, it's crucial to protect the entry point of your application with the well-known conditional statement "if __name__ == '__main__':".
import lib_foo
def some_module():
lib_foo.function_foo()
def main():
some_module()
# here the subprocess stops loading, because __name__ is NOT '__main__'
if __name__ = '__main__':
main()The challenge arises from Windows OS's lack of support for the "fork" process model, a limitation not present in Unix-based systems.
Further details can be explored through these resources:
- [Stack Overflow discussion on multiprocessing and __name__ == '__main__'](https://stackoverflow.com/questions/45110287/workaround-for-using-name-main-in-python-multiprocessing)
- [Python's multiprocessing documentation for Windows](https://docs.python.org/2/library/multiprocessing.html#windows)
Due to this, when main.py is re-imported under a name different from "__main__", references within decorated classes and functions become invalid. To circumvent this, it's advisable to house decorated entities in a separate module. Generally, and particularly on Windows, the main() function should be streamlined to act merely as an entry point, with the substantive logic residing in modules. Additionally, storing settings or configurations in a distinct file is beneficial for centralized access and to leverage features like type hints and auto-completion in your preferred IDE.
The dill serializer, chosen for its broader compatibility, successfully serializes the __main__ context, enabling objects to be pickled to "__main__.lib_foo", "__main__.some_module", "__main__.main", etc. This overcomes the limitations faced when using pickle, which cannot serialize various types including functions with yields, nested functions, and more. Dill enhances functionality by enabling the saving/loading of Python sessions, extraction of source code, and interactive debugging of serialization errors. However, it necessitates that decorated methods and classes not be defined in the __main__ context but within a module.
For more insights on serialization with pickle or dill: - [Stack Overflow discussion on serializing objects in __main__ with pickle or dill](https://stackoverflow.com/questions/45616584/serializing-an-object-in-main-with-pickle-or-dill)
Given the variable duration of the spawning process (due to re-importing modules), the hard timeout section provides guidance on configuring the commencement of timeouts.
An illustration highlights a scenario functional on Linux but problematic on Windows, where the variable "name" and the function "sleep" are not recognized in the spawned process:
main.py:
from time import sleep
from wrapt_timeout_decorator import *
name="my_var_name"
@timeout(5, use_signals=False)
def mytest():
# this example does NOT work on windows, please check the example below !
# You need to move this function into a module to be able to run it on windows.
print("Start ", name)
for i in range(1,10):
sleep(1)
print("{} seconds have passed".format(i))
return i
if __name__ == '__main__':
mytest()here the same example, which will work on Windows:
# my_program_main.py:
import lib_test
def main():
lib_test.mytest()
if __name__ == '__main__':
main()# conf_my_program.py:
class ConfMyProgram(object):
def __init__(self):
self.name:str = 'my_var_name'
conf_my_program = ConfMyProgram()# lib_test.py:
from wrapt_timeout_decorator import *
from time import sleep
from conf_my_program import conf_my_program
# use_signals = False is not really necessary here, it is set automatically under Windows
# but You can force NOT to use Signals under Linux
@timeout(5, use_signals=False)
def mytest():
print("Start ", conf_my_program.name)
for i in range(1,10):
sleep(1)
print("{} seconds have passed".format(i))
return iABADGER1999 highlights in his blog post the potential pitfalls of using signals alongside the TimeoutException. This approach may not be advisable as the exception can be intercepted within the decorated function.
While it's possible to implement a custom Exception derived from the Base Exception Class, this doesn't guarantee the code will behave as anticipated. For an illustrative example, you're encouraged to conduct an experiment using a Jupyter notebook.
import time
from wrapt_timeout_decorator import *
# Considerations for Signal Usage - Handling TimeoutError
# The TimeoutError triggered by a signal might be intercepted within the decorated function.
# Utilizing a custom Exception, derived from the base Exception Class, is a possible workaround.
# Within Python 3.7.1's standard library, there are over 300 instances where your custom timeout might be caught
# if it's based on Exception. Should you base your exception on BaseException,
# there still remain 231 potential catch points.
# To ensure proper timeout management, it's advisable to set `use_signals=False`.
# Consequently, `use_signals` defaults to `False` in this decorator to avoid these issues.
@timeout(5, use_signals=True)
def mytest(message):
try:
print(message)
for i in range(1,10):
time.sleep(1)
print('{} seconds have passed - lets assume we read a big file here'.format(i))
# TimeoutError is a Subclass of OSError - therefore it is catched here !
except OSError:
for i in range(1,10):
time.sleep(1)
print('Whats going on here ? - Ooops the Timeout Exception is catched by the OSError ! {}'.format(i))
except Exception:
# even worse !
pass
except:
# the worst - and exists more then 300x in actual Python 3.7 stdlib Code !
# so You never really can rely that You catch the TimeoutError when using Signals !
pass
if __name__ == '__main__':
try:
mytest('starting')
print('no Timeout Occured')
except TimeoutError():
# this will never be printed because the decorated function catches implicitly the TimeoutError !
print('Timeout Occured')Subprocesses ares utilized by default to implement timeout functionality. This involves forking or spawning subprocesses, each with its own set of considerations and caveats.
- Windows Considerations: On Windows, the spawn method can significantly slow down the process initiation.
- Main Context Protection: It is crucial to protect the
__main__context for compatibility, especially on Windows. See the "Usage with Windows" section for more details. - Pickle Requirements: Function codes and arguments must be pickleable. To accommodate a wider range of types, dill is used for serialization.
- Global Variables: Access to global variables from a child process might not reflect the parent process's state at the time of the fork. Module-level constants are generally unaffected.
- Subprocess Execution: Functions run in a separate subprocess, whether forked or spawned.
- Data Transmission: Parameters and results are communicated through pipes, with dill used for serialization.
- Timeout Management: Absent a result within the specified timeout, the subprocess is terminated using SIGTERM. Ensuring subprocesses can terminate safely is essential; thus, disabling the SIGTERM handler is not advisable.
- Windows Limitation: Only spawn is available on Windows.
- Linux/Unix Options: Options include fork, forkserver, and spawn.
- Fork: Efficiently clones the parent process, including memory space, but may lead to issues with shared resources or in multi-threaded applications.
- Forkserver: Starts a server at program launch, creating new processes upon request for better isolation but at a slower pace due to the server communication requirement.
- Spawn: Initiates a fresh Python interpreter process, ensuring total independence at the cost of slower start-up due to the need for full initialization.
- fork offers speed but can encounter issues with resource sharing or threading.
- forkserver enhances stability and isolation, ideal for applications requiring safety or managing unstable resources.
- spawn provides the highest level of isolation, recommended for a clean start and avoiding shared state complications.
Configure the start method with multiprocessing.set_start_method(method, force=True). This should be done cautiously, ideally once, and within the if
__name__ == '__main__' block to prevent unintended effects.
Since we use multiprocess instead of multiprocessing, we provide a method to set the starting method on both at the same time.
see : set_subprocess_starting_method
For Uvicorn or FastAPI applications, a specific approach to the fork method is recommended to ensure proper signal handling and isolation, facilitated by the dec_mp_reset_signals parameter.
This design aims to reset signal handlers and manage file descriptors in child processes effectively.
You can set that by passing the parameter dec_mp_reset_signals=True to the decorator.
Due to Unix's limitation of having just one ALARM signal per process, it's necessary to set use_signals=False for nested timeouts to function correctly. While the outermost decorator may utilize signals, all inner decorators must have use_signals set to False—which is the default setting. For practical experimentation and to see this behavior in action, you're encouraged to use a Jupyter notebook.
# main.py
import mylib
# this example will work on Windows and Linux
# since the decorated function is not in the __main__ scope but in another module !
if __name__ == '__main__':
mylib.outer()# mylib.py
from wrapt_timeout_decorator import *
import time
# this example will work on Windows and Linux
# since the decorated function is not in the __main__ scope but in another module !
@timeout(1, use_signals=True)
def outer():
inner()
@timeout(5)
def inner():
time.sleep(3)
print("Should never be printed if you call outer()")
评论