Skip to content

Commit da32179

Browse files
committed
gh-163101: Reject NaN deadlines in asyncio.timeout
1 parent 64c20ff commit da32179

4 files changed

Lines changed: 25 additions & 0 deletions

File tree

‎Doc/library/asyncio-task.rst‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -840,6 +840,9 @@ Timeouts
840840

841841
.. versionadded:: 3.11
842842

843+
.. versionchanged:: next
844+
Raises :exc:`ValueError` if *delay* is :data:`~math.nan`.
845+
843846
.. function:: timeout_at(when)
844847

845848
Similar to :func:`asyncio.timeout`, except *when* is the absolute time
@@ -860,6 +863,9 @@ Timeouts
860863

861864
.. versionadded:: 3.11
862865

866+
.. versionchanged:: next
867+
Raises :exc:`ValueError` if *when* is :data:`~math.nan`.
868+
863869
.. function:: wait_for(fut, timeout)
864870
:async:
865871

‎Lib/asyncio/timeouts.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import enum
2+
import math
23

34
from types import TracebackType
45

@@ -54,6 +55,8 @@ def reschedule(self, when: float | None) -> None:
5455
raise RuntimeError(
5556
f"Cannot change state of {self._state.value} Timeout",
5657
)
58+
if when is not None and math.isnan(when):
59+
raise ValueError("Invalid deadline: NaN (not a number)")
5760

5861
self._when = when
5962

‎Lib/test/test_asyncio/test_timeouts.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,16 @@ async def test_timeout_at_disabled(self):
8080
self.assertFalse(cm.expired())
8181
self.assertIsNone(cm.when())
8282

83+
async def test_timeout_nan(self):
84+
with self.assertRaisesRegex(ValueError, "NaN"):
85+
async with asyncio.timeout(float("nan")):
86+
pass
87+
88+
async def test_timeout_at_nan(self):
89+
with self.assertRaisesRegex(ValueError, "NaN"):
90+
async with asyncio.timeout_at(float("nan")):
91+
pass
92+
8393
async def test_timeout_zero(self):
8494
loop = asyncio.get_running_loop()
8595
t0 = loop.time()
@@ -244,6 +254,9 @@ async def f():
244254
self.assertEqual(cm.when(), deadline2)
245255
cm.reschedule(None)
246256
self.assertIsNone(cm.when())
257+
with self.assertRaisesRegex(ValueError, "NaN"):
258+
cm.reschedule(float("nan"))
259+
self.assertIsNone(cm.when())
247260

248261
task.cancel()
249262

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Raise :exc:`ValueError` if the deadline of :func:`asyncio.timeout`,
2+
:func:`asyncio.timeout_at` or :meth:`asyncio.Timeout.reschedule` is a NaN,
3+
matching :func:`asyncio.sleep`.

0 commit comments

Comments
 (0)