diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index 8d5bde09ea9b5b..a7db1c116f47dd 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -640,9 +640,34 @@ def __sleep0(): yield +def _check_delay(delay): + """Check if the value of 'delay' is valid.""" + + import sys + import math + + SEC_TO_NS = 1000 * 1000 * 1000 + + if not isinstance(delay, (int, float)): + raise TypeError(f"{type(delay)} object cannot be interpreted as an integer") + + # According to Modules/timemodule.c + if (delay > sys.maxsize / SEC_TO_NS): + raise OverflowError("timestamp too large to convert to C _PyTime_t") + + if (delay < 0): + raise ValueError("sleep length must be non-negative") + + if (math.isnan(delay)): + raise ValueError("Invalid value NaN (not a number)") + + async def sleep(delay, result=None): """Coroutine that completes after a given time (in seconds).""" - if delay <= 0: + + _check_delay(delay) + + if delay == 0: await __sleep0() return result diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-06-08-16-29-43.gh-issue-105513.M7ueoq.rst b/Misc/NEWS.d/next/Core and Builtins/2023-06-08-16-29-43.gh-issue-105513.M7ueoq.rst new file mode 100644 index 00000000000000..91311d9757258f --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2023-06-08-16-29-43.gh-issue-105513.M7ueoq.rst @@ -0,0 +1 @@ +fix asyncio.sleep(float('nan')) does not raise ValueError bug