### Python: StoppableThread as Parent Class Example Source: https://github.com/kata198/func_timeout/blob/master/README.md Provides an example of how to create a custom stoppable thread by subclassing `func_timeout.StoppableThread.StoppableThread` and implementing the `run` method. It also shows how to instantiate and start the thread. ```Python from func_timeout.StoppableThread import StoppableThread class MyThread(StoppableThread): def run(self): # Code here return myThread = MyThread() # Uncomment next line to start thread in "daemon mode" -- i.e. will terminate/join automatically upon main thread exit #myThread.daemon = True myThread.start() ``` -------------------------------- ### Python func_timeout Basic Usage Example Source: https://github.com/kata198/func_timeout/blob/master/README.rst Illustrates how to use `func_timeout` to execute a function (`doit`) with a 5-second timeout. The example demonstrates proper error handling for `FunctionTimedOut` and other exceptions that the wrapped function might raise. ```Python from func_timeout import func_timeout, FunctionTimedOut # Assume 'doit' is a defined function try: doitReturnValue = func_timeout(5, doit, args=('arg1', 'arg2')) except FunctionTimedOut: print ( "doit('arg1', 'arg2') could not complete within 5 seconds and was terminated.\n") except Exception as e: # Handle any exceptions that doit might raise here pass # Placeholder for actual error handling ``` -------------------------------- ### Python StoppableThread Inheritance Example Source: https://github.com/kata198/func_timeout/blob/master/README.rst Provides an example of creating a custom thread by inheriting from `func_timeout.StoppableThread.StoppableThread`. It shows how to override the `run` method and then instantiate and start the custom thread, including an option for daemon mode. ```Python from func_timeout.StoppableThread import StoppableThread class MyThread(StoppableThread): def run(self): # Code here for the thread's execution return myThread = MyThread() # Uncomment next line to start thread in "daemon mode" -- i.e. will terminate/join automatically upon main thread exit #myThread.daemon = True myThread.start() ``` -------------------------------- ### Python Thread start Method Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html Starts the thread's activity. This method must be called at most once per thread object and arranges for the run() method to be invoked in a separate thread of control. ```APIDOC start(self): Description: Starts the thread's activity. Must be called at most once per thread object. Raises: RuntimeError: If called more than once on the same thread object. ``` -------------------------------- ### Creating and Starting a StoppableThread in Python Source: https://github.com/kata198/func_timeout/blob/master/README.rst This snippet demonstrates how to initialize and start a `StoppableThread` instance. It shows how to pass positional and keyword arguments to the target function and includes an option to run the thread in daemon mode, allowing it to terminate automatically with the main program. ```Python myThread = StoppableThread( target=myFunction, args=('ordered', 'args', 'here'), kwargs={ 'keyword args' : 'here' } ) # Uncomment next line to start thread in "daemon mode" \-\- i.e. will terminate/join automatically upon main thread exit #myThread.daemon = True myThread.start() ``` -------------------------------- ### Starting a StoppableThread in Python Source: https://github.com/kata198/func_timeout/blob/master/README.md This snippet demonstrates how to initialize and start a `StoppableThread` instance. It shows how to pass positional and keyword arguments to the target function and optionally configure the thread to run in daemon mode, allowing it to terminate automatically with the main thread. ```Python myThread = StoppableThread( target=myFunction, args=('ordered', 'args', 'here'), kwargs={ 'keyword args' : 'here' } ) # Uncomment next line to start thread in "daemon mode" -- i.e. will terminate/join automatically upon main thread exit #myThread.daemon = True myThread.start() ``` -------------------------------- ### Python: Example Usage of func_timeout Source: https://github.com/kata198/func_timeout/blob/master/README.md Demonstrates how to use `func_timeout` to limit the execution time of a function and handle `FunctionTimedOut` exceptions. It shows a `try-except` block to catch both `FunctionTimedOut` and other potential exceptions from the wrapped function. ```Python from func_timeout import func_timeout, FunctionTimedOut ... try: doitReturnValue = func_timeout(5, doit, args=('arg1', 'arg2')) except FunctionTimedOut: print ( "doit('arg1', 'arg2') could not complete within 5 seconds and was terminated.\n") except Exception as e: # Handle any exceptions that doit might raise here ``` -------------------------------- ### Python func_set_timeout Decorator Example Source: https://github.com/kata198/func_timeout/blob/master/README.rst Demonstrates applying the `func_set_timeout` decorator to a Python function. This decorator automatically wraps the decorated function with timeout logic, in this case, setting a fixed timeout of 2.5 seconds. ```Python from func_timeout import func_set_timeout @func_set_timeout(2.5) def myFunction(self, arg1, arg2): # Function implementation pass ``` -------------------------------- ### Python: Example Usage of func_set_timeout Decorator Source: https://github.com/kata198/func_timeout/blob/master/README.md Illustrates how to apply the `func_set_timeout` decorator to a function to automatically enforce a timeout. The decorator takes a timeout value, which can be a fixed number or a function/lambda for dynamic timeouts. ```Python @func_set_timeout(2.5) def myFunction(self, arg1, arg2): ... ``` -------------------------------- ### Python Thread ident Data Descriptor Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html Thread identifier of this thread or None if it has not been started. This is a nonzero integer. Thread identifiers may be recycled. ```APIDOC ident (int or None): Description: Thread identifier, or None if not started. Nonzero integer. ``` -------------------------------- ### Defining a Custom BaseException for StoppableThread Termination (Python) Source: https://github.com/kata198/func_timeout/blob/master/README.rst This example demonstrates how to define a custom exception class, `ServerShutdownExceptionType`, that inherits from `BaseException`. Such custom exceptions are recommended for use with `StoppableThread.stop()` to reliably terminate threads, especially when default `Exception` handling might otherwise prevent termination. ```Python class ServerShutdownExceptionType(BaseException): def __init__(self, *args, **kwargs): BaseException.__init__(self, 'Server is shutting down') ``` -------------------------------- ### Python Thread daemon Data Descriptor Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html A boolean value indicating whether this thread is a daemon thread. This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread. ```APIDOC daemon (bool): Description: Indicates if this thread is a daemon thread. Must be set before start(). Raises: RuntimeError: If set after start() is called. ``` -------------------------------- ### Python Example: Unstoppable Loop with Broad Exception Handling Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.html This Python code snippet illustrates a common anti-pattern where a "while True" loop with a broad "except" block (e.g., "except: continue") can prevent a "StoppableThread" from being effectively terminated. The exception raised by "StoppableThread.stop()" is immediately caught, making the thread unresponsive to termination signals. ```Python while True: try: doSomething() except: continue ``` -------------------------------- ### Python Exception Handling Pitfall with StoppableThread Source: https://github.com/kata198/func_timeout/blob/master/README.md This example illustrates a common issue where a broad `except Exception as e: continue` block can prevent a `StoppableThread` from terminating gracefully when an exception is raised by the `stop()` method. It highlights why extending `BaseException` is recommended and suggests a workaround for third-party code. ```Python while True: try: doSomething() except Exception as e: continue ``` -------------------------------- ### Defining a Custom BaseException for StoppableThread Termination Source: https://github.com/kata198/func_timeout/blob/master/README.md This snippet provides an example of defining a custom exception type that extends `BaseException`. Using such a custom exception is recommended for `StoppableThread` to ensure proper termination, especially when dealing with broad `except Exception` blocks. It also shows how to enforce a fixed error message. ```Python class ServerShutdownExceptionType(BaseException): def __init__(self, *args, **kwargs): BaseException.__init__(self, 'Server is shutting down') ``` -------------------------------- ### API Documentation for func_timeout.dafunc Module Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.dafunc.html Comprehensive API reference for the func_timeout.dafunc module, including function signatures, parameters, return types, and exceptions. ```APIDOC Module: func_timeout.dafunc Functions: func_set_timeout(timeout, allowOverride=False) Description: Decorator to run a function with a given/calculated timeout (max execution time). Optionally (if #allowOverride is True), adds a parameter, "forceTimeout", to the function which, if provided, will override the default timeout for that invocation. If #timeout is provided as a lambda/function, it will be called prior to each invocation of the decorated function to calculate the timeout to be used for that call, based on the arguments passed to the decorated function. Parameters: timeout: If float: Default number of seconds max to allow function to execute before throwing FunctionTimedOut. If lambda/function: Called for every invocation of the decorated function (unless #allowOverride=True and "forceTimeout" was passed) to determine the timeout to use based on the arguments to the decorated function. The arguments as passed into the decorated function will be passed to this function. They either must match exactly to what the decorated function has, OR if you prefer to get the *args (list of ordered args) and **kwargs (key : value keyword args form), define your calculate function like: def calculateTimeout(*args, **kwargs): ... or lambda like: calculateTimeout = lambda *args, **kwargs : ... otherwise the args to your calculate function should match exactly the decorated function. allowOverride: (Default: False) If True, adds a keyword argument to the decorated function, "forceTimeout" which, if provided, will override the #timeout. If #timeout was provided as a lambda / function, it will not be called. Throws: FunctionTimedOut - If time allotted passes without function returning naturally. See also: func_timeout func_timeout(timeout, func, args=(), kwargs=None) Description: Runs the given function for up to #timeout# seconds. Raises any exceptions #func# would raise, returns what #func# would return (unless timeout is exceeded), in which case it raises FunctionTimedOut. If the timeout is exceeded, FunctionTimedOut will be raised within the context of the called function every two seconds until it terminates, but will not block the calling thread (a new thread will be created to perform the join). If possible, you should try/except FunctionTimedOut to return cleanly, but in most cases it will 'just work'. Parameters: timeout: - Maximum number of seconds to run #func# before terminating. func: - The function to call. args: - Any ordered arguments to pass to the function. kwargs: - Keyword arguments to pass to the function. Raises: FunctionTimedOut - if #timeout# is exceeded, otherwise anything #func# could raise will be raised. Return: The return value that #func# gives. Data: __all__: ('func_timeout', 'func_set_timeout') ``` -------------------------------- ### Inherited Methods from threading.Thread API Reference Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html API documentation for methods inherited by 'StoppableThread' from Python's standard 'threading.Thread' class. This includes common thread management functions like initialization, status checks, and joining threads. ```APIDOC Methods inherited from threading.Thread: __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None): Description: The standard constructor for a thread. Arguments should always be called with keyword arguments. Parameters: group: None - Reserved for future extension. target: callable - The callable object to be invoked by the run() method. Defaults to None. name: string - The thread name. Defaults to a unique generated name. args: tuple - The argument tuple for the target invocation. Defaults to (). kwargs: dict - A dictionary of keyword arguments for the target invocation. Defaults to {}. daemon: bool - A flag indicating whether the thread is a daemon thread. Note: If a subclass overrides this constructor, it must call the base class constructor (Thread.__init__()) before doing anything else. __repr__(self): Description: Returns the canonical string representation of the thread object. getName(self): Description: Returns the name of the thread. isAlive(self): Description: Returns True if the thread is alive (i.e., has started and not yet terminated). This method is deprecated; use is_alive() instead. isDaemon(self): Description: Returns True if the thread is a daemon thread, False otherwise. is_alive(self): Description: Returns True if the thread is alive. This method returns True from just before the run() method starts until just after the run() method terminates. join(self, timeout=None): Description: Waits until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates, or until the optional timeout occurs. Parameters: timeout: float (Optional) - The maximum time to wait in seconds. If None, the operation will block indefinitely. Returns: None. Call is_alive() after join() to determine if a timeout happened. Raises: RuntimeError if an attempt is made to join the current thread (deadlock) or a thread before it has been started. run(self): Description: The method representing the thread's activity. This method is typically overridden in a subclass to define the thread's behavior. ``` -------------------------------- ### API Documentation for func_timeout.StoppableThread Class Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.StoppableThread.html Detailed API reference for the func_timeout.StoppableThread class, including its constructor, methods defined within the class, and methods inherited from threading.Thread. ```APIDOC Class: func_timeout.StoppableThread Inherits: threading.Thread Constructor: func_timeout.StoppableThread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None) Description: A thread that can be stopped by forcing an exception in the execution context. This works for both C and Python code. Parameters: group: None; reserved for future extension. target: Callable object to be invoked by the run() method. Defaults to None. name: The thread name. Defaults to "Thread-N". args: Argument tuple for the target invocation. Defaults to (). kwargs: Dictionary of keyword arguments for the target invocation. Defaults to {}. daemon: (keyword-only) A boolean value indicating whether the thread is a daemon thread. Notes: If a subclass overrides the constructor, it must call the base class constructor. Beware of unmarked exception handlers (e.g., 'except:') that can prevent the thread from being aborted. Methods defined in func_timeout.StoppableThread: stop(self, exception, raiseEvery=2.0) Description: Stops the thread by repeatedly raising a given exception within its context. Parameters: exception: - The exception class/type to throw (e.g., MyExceptionType), NOT an instance. Recommended to use an exception that inherits from BaseException. raiseEvery: Default 2.0 - The interval in seconds at which the exception will be re-raised until the thread terminates. Returns: None Methods inherited from threading.Thread: __repr__(self) Description: Return repr(self). getName(self) Description: (Deprecated) Returns the thread's name. isAlive(self) Description: Return whether the thread is alive. This method is deprecated; use is_alive() instead. isDaemon(self) Description: Return whether the thread is a daemon thread. is_alive(self) Description: Return whether the thread is alive. Returns True just before the run() method starts until just after the run() method terminates. join(self, timeout=None) Description: Wait until the thread terminates. Blocks the calling thread until the thread whose join() method is called terminates (normally or via unhandled exception) or until the optional timeout occurs. Parameters: timeout: Optional - Timeout in seconds. If None, the operation will block indefinitely. Notes: This method always returns None. You must call is_alive() after join() to determine if a timeout occurred. A thread can be joined many times. Raises RuntimeError if an attempt is made to join the current thread or a thread before it has been started. ``` -------------------------------- ### Function Timeout Exception and Return Behavior Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html Details the conditions under which the `FunctionTimedOut` exception is raised, its non-blocking nature, recommended handling, and the expected return value of the timed-out function. ```APIDOC FunctionTimedOut Exception: Raised: - If the specified timeout is exceeded during function execution. - Within the context of the called function every two seconds until termination (non-blocking for calling thread). Handling: - Recommended to use try/except FunctionTimedOut for clean termination. Behavior: - Does not block the calling thread (a new thread is created for join). Return Value: - The value returned by the decorated function (`func`). ``` -------------------------------- ### Module Global Variables and Version Information Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html Lists the public symbols exposed by the `func_timeout` module and its version tuple. ```APIDOC Module Variables: __all__: ('func_timeout', 'func_set_timeout', 'FunctionTimedOut', 'StoppableThread') __version_tuple__: (4, 3, 5) ``` -------------------------------- ### func_timeout Library Behavior and Module API Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.html Details the exception handling and return behavior of functions wrapped by `func_timeout`, specifically regarding the `FunctionTimedOut` exception. It also lists the public symbols exposed by the module and its version information. ```APIDOC func_timeout Library Behavior: @raises: - FunctionTimedOut: If the timeout is exceeded. - Other exceptions: Any exception the wrapped function ('func') could raise. FunctionTimedOut Handling: - Raised within the context of the called function every two seconds until it terminates. - Does not block the calling thread (a new thread is created to perform the join). - Recommendation: Use try/except FunctionTimedOut for clean return, though it often 'just works'. @return: - The return value that the wrapped function ('func') gives. Module-level Variables: - __all__: ('func_timeout', 'func_set_timeout', 'FunctionTimedOut', 'StoppableThread') - __version_tuple__: (4, 3, 5) ``` -------------------------------- ### APIDOC: func_timeout.py2_raise Module and raise_exception Function Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.py2_raise.html This API documentation describes the func_timeout.py2_raise module, which is specific to Python 2 and provides functionality for handling alternate tracebacks. It details the 'raise_exception' function, including its purpose and parameters. ```APIDOC Module: func_timeout.py2_raise Description: Python2 allows specifying an alternate traceback. Functions: raise_exception(exception) Description: Allows specifying an alternate traceback. Parameters: exception: The exception object to be raised. ``` -------------------------------- ### StoppableThread Class API Reference Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.StoppableThread.html Detailed API reference for the `StoppableThread` class, outlining its methods and inherited data descriptors, including their purpose and usage. ```APIDOC StoppableThread: Methods: run(self): Description: Method representing the thread's activity. You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively. setDaemon(self, daemonic): Description: Sets the daemon flag for the thread. Parameters: daemonic: boolean - Whether the thread should be a daemon thread. setName(self, name): Description: Sets the name of the thread. Parameters: name: string - The name to assign to the thread. start(self): Description: Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object. Data descriptors inherited from threading.Thread: __dict__: Description: dictionary for instance variables (if defined) __weakref__: Description: list of weak references to the object (if defined) daemon: Description: A boolean value indicating whether this thread is a daemon thread. This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False. The entire Python program exits when no alive non-daemon threads are left. ident: Description: Thread identifier of this thread or None if it has not been started. This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited. name: Description: A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. ``` -------------------------------- ### Python func_timeout.exceptions.FunctionTimedOut Class API Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.html Detailed API documentation for the `FunctionTimedOut` exception class, which is raised when a function times out. It includes constructor parameters, properties for accessing timeout details, and a method for retrying the timed-out function. ```APIDOC class FunctionTimedOut(builtins.BaseException): Description: Exception raised when a function times out. Constructor: __init__(self, msg='', timedOutAfter=None, timedOutFunction=None, timedOutArgs=None, timedOutKwargs=None) Description: Create this exception type. You should not need to do this outside of testing, it will be created by the func_timeout API. Parameters: msg (str): A predefined message, otherwise we will attempt to generate one from the other arguments. timedOutAfter (None/float): Number of seconds before timing-out. Filled-in by API, None will produce "Unknown". timedOutFunction (None/function): Reference to the function that timed-out. Filled-in by API. None will produce "Unknown Function". timedOutArgs (None/tuple/list): List of fixed-order arguments (*args), or None for no args. timedOutKwargs (None/dict): Dict of keyword arg (**kwargs) names to values, or None for no kwargs. Properties: timedOutAfter: Number of seconds before timeout was triggered. timedOutFunction: Function called which timed out. timedOutArgs: Ordered args to function. timedOutKwargs: Keyword args to function. Methods: getMsg(self) Description: Generate a default message based on parameters to FunctionTimedOut exception. Returns: str - Message. retry(self, timeout='RETRY_SAME_TIMEOUT') Description: Retry the timed-out function with same arguments. Parameters: timeout (float/RETRY_SAME_TIMEOUT/None): RETRY_SAME_TIMEOUT: Will retry the function same args, same timeout. float/int: Will retry the function same args with provided timeout. None: Will retry function same args no timeout. Returns: Returnval from function. Method Resolution Order: FunctionTimedOut builtins.BaseException builtins.object Inherited Methods from builtins.BaseException: __delattr__(self, name, /) __getattribute__(self, name, /) __reduce__(...) __repr__(self, /) __setattr__(self, name, value, /) __setstate__(...) __str__(self, /) with_traceback(...) Inherited Static Methods from builtins.BaseException: __new__(*args, **kwargs) from builtins.type Inherited Data Descriptors from builtins.BaseException: __cause__ __context__ __dict__ __suppress_context__ __traceback__ args Data Descriptors defined here: __weakref__: list of weak references to the object (if defined) ``` -------------------------------- ### StoppableThread Class API Reference Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.html Detailed API documentation for the "StoppableThread" class, including its unique "stop" method for forceful termination, and key methods inherited from "threading.Thread". ```APIDOC StoppableThread Class: Description: A thread that can be stopped by forcing an exception in the execution context. This works both to interrupt code that is in C or in python code, at either the next call to a python function, or the next line in python code. Inherits from: threading.Thread, builtins.object Methods defined in StoppableThread: stop(self, exception, raiseEvery=2.0) Description: Stops the thread by raising a given exception. Parameters: exception: - Exception to throw. Likely, you want to use something that inherits from BaseException (so except Exception as e: continue; isn't a problem). This should be a class/type, NOT an instance, i.e. MyExceptionType not MyExceptionType(). raiseEvery: Default 2.0 - We will keep raising this exception every #raiseEvery seconds, until the thread terminates. If your code traps a specific exception type, this will allow you #raiseEvery seconds to cleanup before exit. If you're calling third-party code you can't control, which catches BaseException, set this to a low number to break out of their exception handler. Returns: Methods inherited from threading.Thread: __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None) Description: This constructor should always be called with keyword arguments. Parameters: group: Should be None; reserved for future extension when a ThreadGroup class is implemented. target: The callable object to be invoked by the run() method. Defaults to None, meaning nothing is called. name: The thread name. By default, a unique name is constructed of the form "Thread-N" where N is a small decimal number. args: The argument tuple for the target invocation. Defaults to (). kwargs: A dictionary of keyword arguments for the target invocation. Defaults to {}. Notes: If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. __repr__(self) Description: Return repr(self). getName(self) isAlive(self) Description: Return whether the thread is alive. This method is deprecated, use is_alive() instead. isDaemon(self) is_alive(self) Description: Return whether the thread is alive. This method returns True just before the run() method starts until just after the run() method terminates. The module function enumerate() returns a list of all alive threads. join(self, timeout=None) Description: Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates -- either normally or through an unhandled exception or until the optional timeout occurs. Parameters: timeout: Optional - If present and not None, a floating point number specifying a timeout for the operation in seconds (or fractions thereof). Notes: As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened -- if the thread is still alive, the join() call timed out. When the timeout argument is not present or None, the operation will block until the thread terminates. A thread can be joined many times. join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join a thread before it has been started and attempts to do so raises the same exception. run(self) Description: Method representing the thread's activity. ``` -------------------------------- ### Illustrate Uncatchable Exception Handling in Python Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html This Python code snippet demonstrates a common pitfall where a broad 'except' block can prevent a thread from being forcefully stopped by an injected exception, as the exception is immediately caught and ignored, leading to an infinite loop. ```Python while True: try: doSomething() except: continue ``` -------------------------------- ### Python func_timeout Function API Source: https://github.com/kata198/func_timeout/blob/master/README.rst Detailed API documentation for the `func_timeout` function, outlining its purpose to run a given function with a specified timeout. It specifies parameters like `timeout` (float), `func` (function), `args` (tuple), and `kwargs` (dict/None), and notes that it raises `FunctionTimedOut` or exceptions from the wrapped function. ```APIDOC func_timeout(timeout: float, func: callable, args: tuple = (), kwargs: dict = None) -> Any: Description: Runs the given function for up to #timeout# seconds. Raises: - FunctionTimedOut: If #timeout# is exceeded. - Any exception #func# would raise. Returns: The return value that #func# gives. ``` -------------------------------- ### APIDOC: FunctionTimedOut Exception retry Method Source: https://github.com/kata198/func_timeout/blob/master/README.md Documents the `retry` method of the `FunctionTimedOut` exception, detailing its overloaded arguments for retrying the timed-out function with different timeout configurations. ```APIDOC FunctionTimedOut.retry(): - No argument: Retry same args, same function, same timeout - Number argument: Retry same args, same function, provided timeout - None: Retry same args, same function, no timeout ``` -------------------------------- ### Python func_timeout Function Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html Runs the given function for up to a specified number of seconds. Raises any exceptions the function would raise, or FunctionTimedOut if the timeout is exceeded. ```APIDOC func_timeout(timeout, func, args=(), kwargs=None): Description: Runs the given function for up to #timeout# seconds. Parameters: timeout (float): Maximum number of seconds to run #func# before terminating. func (function): The function to call. args (tuple): Any ordered arguments to pass to the function. kwargs (dict or None): Keyword arguments to pass to the function. Returns: The return value of #func#, if it completes within the timeout. Raises: FunctionTimedOut: If the timeout is exceeded. Any exceptions #func# would raise. ``` -------------------------------- ### StoppableThread Methods Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.html Methods associated with a `StoppableThread` object, including controlling its daemon status, setting its name, and initiating its activity. The `run` method is the core execution logic that can be overridden. ```APIDOC StoppableThread: run(): Description: May be overridden in a subclass. Invokes the callable object passed to the object's constructor as the target argument, with sequential and keyword arguments from args and kwargs. setDaemon(self, daemonic): Description: Sets the daemon flag for the thread. Parameters: daemonic: boolean - Whether this thread is a daemon thread. setName(self, name): Description: Sets the name of the thread. Parameters: name: string - The new name for the thread. start(): Description: Starts the thread's activity. Must be called at most once per thread object. Arranges for the object's run() method to be invoked in a separate thread of control. Raises RuntimeError if called more than once on the same thread object. ``` -------------------------------- ### StoppableThread Class API Reference Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html Detailed API documentation for the 'StoppableThread' class, a custom Python thread implementation that supports forceful termination. This section covers its constructor signature and the 'stop' method, which injects an exception into the thread's execution. ```APIDOC Class: StoppableThread Description: A thread that can be stopped by forcing an exception in the execution context. Inherits: threading.Thread, builtins.object Constructor Signature: StoppableThread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None) Methods defined in StoppableThread: stop(self, exception, raiseEvery=2.0): Description: Stops the thread by raising a given exception. Parameters: exception: - The exception class to throw. It is recommended to use a type that inherits from BaseException to avoid being caught by common 'except Exception' blocks. This parameter should be the class itself (e.g., MyExceptionType), not an instance (e.g., MyExceptionType()). raiseEvery: (Default: 2.0) - The interval in seconds at which the exception will be re-raised until the thread terminates. This allows for cleanup or breaking out of persistent exception handlers. Returns: None ``` -------------------------------- ### FunctionTimedOut Class API Reference Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.exceptions.html Detailed API documentation for the `FunctionTimedOut` exception class, which is raised when a function execution exceeds its allotted time. It provides properties to inspect the timed-out function and arguments, and a method to retry the function. ```APIDOC class FunctionTimedOut(builtins.BaseException): Description: Exception raised when a function times out. Properties: timedOutAfter: Number of seconds before timeout was triggered. timedOutFunction: Function called which timed out. timedOutArgs: Ordered arguments passed to the function. timedOutKwargs: Keyword arguments passed to the function. Methods: __init__(self, msg='', timedOutAfter=None, timedOutFunction=None, timedOutArgs=None, timedOutKwargs=None) Description: Creates an instance of the FunctionTimedOut exception. Typically created by the func_timeout API. Parameters: msg : A predefined message, or one generated from other arguments. timedOutAfter : Number of seconds before timing-out. Filled by API, None produces "Unknown". timedOutFunction : Reference to the function that timed-out. Filled by API, None produces "Unknown Function". timedOutArgs : List of fixed-order arguments (*args), or None. timedOutKwargs : Dictionary of keyword arguments (**kwargs), or None. getMsg(self) Description: Generates a default message based on the exception's parameters. Returns: - The generated message. retry(self, timeout='RETRY_SAME_TIMEOUT') Description: Retries the timed-out function with the same arguments. Parameters: timeout : 'RETRY_SAME_TIMEOUT': Retries with the original timeout. : Retries with the provided timeout. None: Retries without any timeout. Returns: The return value from the retried function. Class Variables: RETRY_SAME_TIMEOUT: 'RETRY_SAME_TIMEOUT' __all__: ('FunctionTimedOut', 'RETRY_SAME_TIMEOUT') ``` -------------------------------- ### Python Thread __weakref__ Data Descriptor Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html List of weak references to the thread object. ```APIDOC __weakref__ (list): Description: List of weak references to the object (if defined). ``` -------------------------------- ### Python func_timeout.StoppableThread Class API Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.html API documentation for the `StoppableThread` class, which inherits from `threading.Thread`. ```APIDOC class StoppableThread(threading.Thread) ``` -------------------------------- ### Python Thread __dict__ Data Descriptor Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html Dictionary for instance variables of the thread object. ```APIDOC __dict__ (dict): Description: Dictionary for instance variables (if defined). ``` -------------------------------- ### threading.Thread Inherited Data Descriptors Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.html Data descriptors inherited from the standard `threading.Thread` class, providing information and control over thread properties like instance variables, weak references, daemon status, identifier, and name. ```APIDOC threading.Thread Data Descriptors: __dict__: Description: Dictionary for instance variables (if defined). __weakref__: Description: List of weak references to the object (if defined). daemon: Type: boolean Description: A boolean value indicating whether this thread is a daemon thread. Must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread. The entire Python program exits when no alive non-daemon threads are left. ident: Type: integer or None Description: Thread identifier of this thread or None if it has not been started. This is a nonzero integer. Thread identifiers may be recycled. The identifier is available even after the thread has exited. name: Type: string Description: A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. ``` -------------------------------- ### Python Thread name Data Descriptor Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. ```APIDOC name (str): Description: A string for identification purposes only. No semantic meaning. ``` -------------------------------- ### Python func_timeout.py3_raise.raise_exception Function API Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.py3_raise.html Documents the `raise_exception` function within the `func_timeout.py3_raise` module. This function implements the behavior specified in PEP 409, allowing an exception to be raised without implicitly chaining it to the current exception context. This prevents issues where wrappers, such as 'funcwrap', might be unintentionally included in the exception traceback. This functionality is exclusive to Python 3.3 and newer versions. ```APIDOC raise_exception(exception) Purpose: Raises an exception with the chained exception context disabled. PEP Reference: PEP 409 Availability: Python 3.3+ Notes: Prevents implicit chaining of wrappers (e.g., 'funcwrap') to the raised exception context. ``` -------------------------------- ### Python func_timeout.exceptions.FunctionTimedOut Class API Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html Detailed API documentation for the `FunctionTimedOut` exception class within the `func_timeout` Python package. This class is raised when a function exceeds its allocated execution time and provides properties to inspect the timeout event and a method to retry the timed-out function. ```APIDOC class FunctionTimedOut(builtins.BaseException): Description: Exception raised when a function times out. Properties: timedOutAfter: Number of seconds before timeout was triggered. timedOutFunction: Function called which timed out. timedOutArgs: Ordered args to function. timedOutKwargs: Keyword args to function. Methods: __init__(self, msg='', timedOutAfter=None, timedOutFunction=None, timedOutArgs=None, timedOutKwargs=None): Description: Create this exception type. You should not need to do this outside of testing, it will be created by the func_timeout API. Parameters: msg (str): A predefined message, otherwise we will attempt to generate one from the other arguments. timedOutAfter (None/float): Number of seconds before timing-out. Filled-in by API, None will produce "Unknown". timedOutFunction (None/function): Reference to the function that timed-out. Filled-in by API. None will produce "Unknown Function". timedOutArgs (None/tuple/list): List of fixed-order arguments (*args), or None for no args. timedOutKwargs (None/dict): Dict of keyword arg (**kwargs) names to values, or None for no kwargs. getMsg(self): Description: Generate a default message based on parameters to FunctionTimedOut exception. Returns: str - Message. retry(self, timeout='RETRY_SAME_TIMEOUT'): Description: Retry the timed-out function with same arguments. Parameters: timeout (float/RETRY_SAME_TIMEOUT/None): RETRY_SAME_TIMEOUT: Will retry the function same args, same timeout. float/int: Will retry the function same args with provided timeout. None: Will retry function same args no timeout. Returns: Returnval from function. Inherited Methods from builtins.BaseException: __delattr__(self, name, /) __getattribute__(self, name, /) __reduce__(...) __repr__(self, /) __setattr__(self, name, value, /) __setstate__(...) __str__(self, /) with_traceback(...) Inherited Static Methods from builtins.BaseException: __new__(*args, **kwargs) Inherited Data Descriptors from builtins.BaseException: __cause__ __context__ __dict__ __suppress_context__ __traceback__ args ``` -------------------------------- ### Python Thread setDaemon Method Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html Sets the daemon flag for the thread. A daemon thread will exit automatically when the main program exits. ```APIDOC setDaemon(self, daemonic): Description: Sets the daemon flag for the thread. Parameters: daemonic (bool): True to make the thread a daemon thread, False otherwise. ``` -------------------------------- ### Python FunctionTimedOut Exception retry() Method API Source: https://github.com/kata198/func_timeout/blob/master/README.rst API documentation for the `retry` method of the `FunctionTimedOut` exception. This method allows re-executing the original function that timed out, with options to use the same timeout, a new specified timeout, or no timeout. ```APIDOC FunctionTimedOut.retry(): Description: Retries the function that previously timed out. Overloads: - retry(): Retries with the same arguments, function, and timeout. - retry(timeout: float): Retries with the same arguments and function, but with the provided new timeout. - retry(timeout: None): Retries with the same arguments and function, but with no timeout. ``` -------------------------------- ### API Reference: StoppableThread.stop() Method Source: https://github.com/kata198/func_timeout/blob/master/README.md Detailed API documentation for the `stop` method of the `StoppableThread` class. This method is used to terminate a running thread by raising a specified exception type within its context. It explains the parameters `exception` and `raiseEvery`, their types, and their impact on thread termination and cleanup. ```APIDOC StoppableThread.stop(self, exception, raiseEvery=2.0) description: Stops the thread by raising a given exception. parameters: exception: type: Exception type (class/type, NOT an instance) description: Exception to throw. Recommended to use something that inherits from BaseException. Must be instantiable with no arguments. raiseEvery: type: float default: 2.0 description: Interval in seconds at which the exception will be repeatedly raised until the thread terminates. Allows for cleanup time or breaking out of third-party exception handlers. returns: None ``` -------------------------------- ### func_timeout Function Source: https://github.com/kata198/func_timeout/blob/master/doc/func_timeout.html A utility function to execute another function with a specified timeout. It raises an exception if the function exceeds the allotted time. ```APIDOC func_timeout(timeout, func, args=(), kwargs=None): Type: Function Description: Runs the given function for up to #timeout# seconds. Raises any exceptions #func# would raise, returns what #func# would return (unless timeout is exceeded), in which case it raises FunctionTimedOut. Parameters: timeout: float - Maximum number of seconds to run #func# before terminating. func: function - The function to call. args: tuple (Default: ()) Any ordered arguments to pass to the function. kwargs: dict/None (Default: None) Keyword arguments to pass to the function. ``` -------------------------------- ### Python Thread setName Method Source: https://github.com/kata198/func_timeout/blob/master/doc/index.html Sets the name of the thread for identification purposes. ```APIDOC setName(self, name): Description: Sets the name of the thread. Parameters: name (str): The new name for the thread. ```