MCPcopy Index your code
hub / github.com/python/cpython / Timeout

Class Timeout

Lib/asyncio/timeouts.py:25–140  ·  view source on GitHub ↗

Asynchronous context manager for cancelling overdue coroutines. Use `timeout()` or `timeout_at()` rather than instantiating this class directly.

Source from the content-addressed store, hash-verified

23
24
25class Timeout:
26 """Asynchronous context manager for cancelling overdue coroutines.
27
28 Use `timeout()` or `timeout_at()` rather than instantiating this class directly.
29 """
30
31 def __init__(self, when: float | None) -> None:
32 """Schedule a timeout that will trigger at a given loop time.
33
34 - If `when` is `None`, the timeout will never trigger.
35 - If `when < loop.time()`, the timeout will trigger on the next
36 iteration of the event loop.
37 """
38 self._state = _State.CREATED
39
40 self._timeout_handler: events.TimerHandle | None = None
41 self._task: tasks.Task | None = None
42 self._when = when
43
44 def when(self) -> float | None:
45 """Return the current deadline."""
46 return self._when
47
48 def reschedule(self, when: float | None) -> None:
49 """Reschedule the timeout."""
50 if self._state is not _State.ENTERED:
51 if self._state is _State.CREATED:
52 raise RuntimeError("Timeout has not been entered")
53 raise RuntimeError(
54 f"Cannot change state of {self._state.value} Timeout",
55 )
56
57 self._when = when
58
59 if self._timeout_handler is not None:
60 self._timeout_handler.cancel()
61
62 if when is None:
63 self._timeout_handler = None
64 else:
65 loop = events.get_running_loop()
66 if when <= loop.time():
67 self._timeout_handler = loop.call_soon(self._on_timeout)
68 else:
69 self._timeout_handler = loop.call_at(when, self._on_timeout)
70
71 def expired(self) -> bool:
72 """Is timeout expired during execution?"""
73 return self._state in (_State.EXPIRING, _State.EXPIRED)
74
75 def __repr__(self) -> str:
76 info = ['']
77 if self._state is _State.ENTERED:
78 when = round(self._when, 3) if self._when is not None else None
79 info.append(f"when={when}")
80 info_str = ' '.join(info)
81 return f"<Timeout [{self._state.value}]{info_str}>"
82

Callers 2

timeoutFunction · 0.85
timeout_atFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…