|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import _thread |
| 4 | +import threading |
| 5 | + |
| 6 | + |
| 7 | +class TimeoutError(BaseException): |
| 8 | + pass |
| 9 | + |
| 10 | + |
| 11 | +class Timeout: |
| 12 | + """Timeout context manager.""" |
| 13 | + |
| 14 | + __slots__ = ( |
| 15 | + '_seconds', '_name', '_raise_exc', '_timer', '_expired', '_exception', |
| 16 | + ) |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + seconds: float, |
| 21 | + name: str = 'Timeout', |
| 22 | + raise_exc: bool = True, |
| 23 | + ) -> None: |
| 24 | + """ |
| 25 | + Uses a thread to track the time spent in a context block and forces an |
| 26 | + exit (and optionally raises a `TimeoutError`) if the execution time |
| 27 | + exceeds a given number of seconds. See the notes for important details |
| 28 | + on edge cases where this may not work as expected. |
| 29 | +
|
| 30 | + Parameters |
| 31 | + ---------- |
| 32 | + seconds : float |
| 33 | + Number of seconds before timing out. |
| 34 | + name : str, optional |
| 35 | + Name to identify the block in exit messages, by default 'Timeout'. |
| 36 | + raise_exc : bool, optional |
| 37 | + If True, raise a `TimeoutError` on exit when the given time limit is |
| 38 | + exceeded. Use False to handle the timeout manually. |
| 39 | +
|
| 40 | + Notes |
| 41 | + ----- |
| 42 | + The `KeyboardInterrupt` that is used to force the exit of the main |
| 43 | + thread may not be immediate, depending on the state of the main thread. |
| 44 | + For example, if you are running `time.sleep`, the interruption will not |
| 45 | + be raised until the sleep is complete. |
| 46 | +
|
| 47 | + If you are using extensions that are not written in pure Python, the |
| 48 | + interruption may not be raised at all, depending on how that extension |
| 49 | + was written to catch and handle exceptions. |
| 50 | +
|
| 51 | + Examples |
| 52 | + -------- |
| 53 | + The `Timeout` class is used as a context manager, as shown below. Here, |
| 54 | + we force a timeout by setting the time limit to 1/1000 of the execution |
| 55 | + time to complete the `slow_fibonacci` function. |
| 56 | +
|
| 57 | + .. code-block:: python |
| 58 | +
|
| 59 | + def slow_fibonacci(n): |
| 60 | + if n < 2: |
| 61 | + return n |
| 62 | + return slow_fibonacci(n-1) + slow_fibonacci(n-2) |
| 63 | +
|
| 64 | + with Timer() as timer: |
| 65 | + result = slow_fibonacci(30) |
| 66 | +
|
| 67 | + exec_time = timer.elapsed_time |
| 68 | + time_limit = exec_time / 1000 |
| 69 | +
|
| 70 | + with Timeout(time_limit) as timeout: |
| 71 | + result = slow_fibonacci(30) |
| 72 | +
|
| 73 | + By default, the context manager will raise an exception if the context |
| 74 | + block exceeds the set time limit. If you want to suppress this behavior, |
| 75 | + and handle it manually you can do so using `raise_exc=False`. |
| 76 | +
|
| 77 | + .. code-block:: python |
| 78 | +
|
| 79 | + with Timeout(time_limit, raise_exc=False) as timeout: |
| 80 | + result = slow_fibonacci(30) |
| 81 | +
|
| 82 | + if timeout.expired: |
| 83 | + raise timeout.exception |
| 84 | +
|
| 85 | + Since we use a `KeyboardInterrupt` to stop the main thread, you may also |
| 86 | + want to differentiate between user-raised interrupts and timeouts. This |
| 87 | + also requires setting `raise_exc=False` to prevent an exception on exit. |
| 88 | +
|
| 89 | + .. code-block:: python |
| 90 | +
|
| 91 | + with Timeout(time_limit, raise_exc=False) as timeout: |
| 92 | +
|
| 93 | + try: |
| 94 | + result = slow_fibonacci(30) |
| 95 | + except KeyboardInterrupt: |
| 96 | + if timeout.expired: |
| 97 | + print('Timeout expired.') |
| 98 | + else: |
| 99 | + print('User interrupt.') # or raise to stop execution |
| 100 | +
|
| 101 | + While demonstrated with a standin function for the Fibonacci sequence, |
| 102 | + this context manager can be used with any block and can help catch and |
| 103 | + cancel long-running operations. Note that the `Timer` and `Timeout` |
| 104 | + utilities can also be used in the same context block, as demonstrated |
| 105 | + below. |
| 106 | +
|
| 107 | + .. code-block:: python |
| 108 | +
|
| 109 | + with Timer() as timer, Timeout(1000*exec_time) as timeout: |
| 110 | + result = slow_fibonacci(30) |
| 111 | +
|
| 112 | + print(f"{timeout.expired=}") # should be False since limit is high |
| 113 | + timer.print_elapsed() |
| 114 | +
|
| 115 | + """ |
| 116 | + self._name = name |
| 117 | + self._seconds = seconds |
| 118 | + self._raise_exc = raise_exc |
| 119 | + |
| 120 | + self._timer = None |
| 121 | + self._expired = False |
| 122 | + self._exception = TimeoutError( |
| 123 | + f"{self._name} exceeded {self._seconds:.2f} seconds." |
| 124 | + ) |
| 125 | + |
| 126 | + def __enter__(self) -> Timeout: |
| 127 | + """Create and start the timer when entering the context block.""" |
| 128 | + self._timer = threading.Timer(self._seconds, self._interrupt) |
| 129 | + self._timer.start() |
| 130 | + |
| 131 | + self._expired = False |
| 132 | + |
| 133 | + return self |
| 134 | + |
| 135 | + def __exit__(self, exc_type, exc_val, exc_tb) -> bool: |
| 136 | + """If the timer is still running, cancel, reset, and handle errors.""" |
| 137 | + if self._timer: |
| 138 | + self._timer.cancel() |
| 139 | + self._timer = None |
| 140 | + |
| 141 | + if self.expired and self._raise_exc: |
| 142 | + raise self.exception from None |
| 143 | + elif self.expired and not self._raise_exc: |
| 144 | + return True # suppress if expired but not raising |
| 145 | + |
| 146 | + return False # don't suppress exceptions |
| 147 | + |
| 148 | + @property |
| 149 | + def expired(self) -> bool: |
| 150 | + """Whether the timer has expired.""" |
| 151 | + return self._expired |
| 152 | + |
| 153 | + @property |
| 154 | + def exception(self) -> TimeoutError: |
| 155 | + """The exception to raise if the timer expired.""" |
| 156 | + return self._exception |
| 157 | + |
| 158 | + def _interrupt(self) -> None: |
| 159 | + """ |
| 160 | + Define the interruption to use when the timer runs out. Here the main |
| 161 | + thread is interrupted with KeyboardInterrupt and a flag is set to True |
| 162 | + to provide a way to differentiate from user-raised interrupts. |
| 163 | +
|
| 164 | + """ |
| 165 | + self._expired = True |
| 166 | + _thread.interrupt_main() # raises KeyboardInterrupt |
0 commit comments