call_with_timeout

snippets.call_with_timeout.call_with_timeout(timeout: float, target: Callable, *args, **kwargs) Any

Call a target with a timeout and return its result.

Parameters:
  • timeout – Number of seconds to wait for a result.

  • target – Callable to evaluate which must be serializable with pickle.

  • *args – Positional arguments passed to target.

  • **kwargs – Keyword arguments passed to target.

Returns:

Value returned by target(*args, **kwargs).

Raises:

TimeoutError – If the target does not complete within the timeout.

Example

>>> from snippets.call_with_timeout import call_with_timeout
>>> from time import sleep

>>> call_with_timeout(1.0, " ".join, ["Hello", "world!"])
'Hello world!'

>>> call_with_timeout(1.0, sleep, 2.0)
Traceback (most recent call last):
    ...
TimeoutError: call to <built-in function sleep> did not complete in 1.0
seconds