]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-105331: Change `asyncio.sleep` to raise ``ValueError` for nan (#105641)
authorJay <74105438+weijay0804@users.noreply.github.com>
Mon, 12 Jun 2023 20:29:02 +0000 (04:29 +0800)
committerGitHub <noreply@github.com>
Mon, 12 Jun 2023 20:29:02 +0000 (20:29 +0000)
Co-authored-by: Guido van Rossum <gvanrossum@gmail.com>
Co-authored-by: Kumar Aditya <59607654+kumaraditya303@users.noreply.github.com>
Doc/library/asyncio-task.rst
Lib/asyncio/tasks.py
Lib/test/test_asyncio/test_tasks.py
Misc/NEWS.d/next/Core and Builtins/2023-06-11-09-14-30.gh-issue-105331.nlZvoW.rst [new file with mode: 0644]

index fe8d028150403d0dfee1782a3814667a8ac199f2..3618bcb6d7c6b527eb89c55e0dff2fc4f9ca478e 100644 (file)
@@ -426,6 +426,9 @@ Sleeping
    .. versionchanged:: 3.10
       Removed the *loop* parameter.
 
+   .. versionchanged:: 3.13
+      Raises :exc:`ValueError` if *delay* is :data:`~math.nan`.
+
 
 Running Tasks Concurrently
 ==========================
index 8d5bde09ea9b5b2bb91d3675809fb916c803aede..4250bb0753879a91137ab90bc855ef68a9547ede 100644 (file)
@@ -15,6 +15,7 @@ import contextvars
 import functools
 import inspect
 import itertools
+import math
 import types
 import warnings
 import weakref
@@ -646,6 +647,9 @@ async def sleep(delay, result=None):
         await __sleep0()
         return result
 
+    if math.isnan(delay):
+        raise ValueError("Invalid delay: NaN (not a number)")
+
     loop = events.get_running_loop()
     future = loop.create_future()
     h = loop.call_later(delay,
index 6e8a51ce2555d55f4cf76161ddb58a24c8362be9..4dfaff847edb907714b68ce2a5301547de0c22c0 100644 (file)
@@ -1609,6 +1609,21 @@ class BaseTaskTests:
         self.assertEqual(t.result(), 'yeah')
         self.assertAlmostEqual(0.1, loop.time())
 
+    def test_sleep_when_delay_is_nan(self):
+
+        def gen():
+            yield
+
+        loop = self.new_test_loop(gen)
+
+        async def sleeper():
+            await asyncio.sleep(float("nan"))
+
+        t = self.new_task(loop, sleeper())
+
+        with self.assertRaises(ValueError):
+            loop.run_until_complete(t)
+
     def test_sleep_cancel(self):
 
         def gen():
diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-06-11-09-14-30.gh-issue-105331.nlZvoW.rst b/Misc/NEWS.d/next/Core and Builtins/2023-06-11-09-14-30.gh-issue-105331.nlZvoW.rst
new file mode 100644 (file)
index 0000000..4a3fee0
--- /dev/null
@@ -0,0 +1,2 @@
+Raise :exc:`ValueError` if the ``delay`` argument to :func:`asyncio.sleep` is a NaN (matching :func:`time.sleep`).
+