diff --git a/Lib/test/test_time.py b/Lib/test/test_time.py index 1147997d8d86bf..cd6c08f183ff95 100644 --- a/Lib/test/test_time.py +++ b/Lib/test/test_time.py @@ -167,6 +167,11 @@ def test_sleep_exceptions(self): self.assertRaises(ValueError, time.sleep, -1) self.assertRaises(ValueError, time.sleep, -0.1) + # Improved exception #81267 + with self.assertRaises(TypeError) as errmsg: + time.sleep([]) + self.assertIn("integer or float", str(errmsg.exception)) + def test_sleep(self): for value in [-0.0, 0, 0.0, 1e-100, 1e-9, 1e-6, 1, 1.2]: with self.subTest(value=value): diff --git a/Misc/NEWS.d/next/Library/2025-03-10-20-23-00.gh-issue-81267.a39381.rst b/Misc/NEWS.d/next/Library/2025-03-10-20-23-00.gh-issue-81267.a39381.rst new file mode 100644 index 00000000000000..9c9a86d30e2450 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-03-10-20-23-00.gh-issue-81267.a39381.rst @@ -0,0 +1,2 @@ +Correct :func:`time.sleep` error message when an object that cannot be interpreted +as an integer or float is provided. diff --git a/Python/pytime.c b/Python/pytime.c index b10d5cf927b7e1..2ca92037c2e2f1 100644 --- a/Python/pytime.c +++ b/Python/pytime.c @@ -594,26 +594,30 @@ pytime_from_object(PyTime_t *tp, PyObject *obj, _PyTime_round_t round, } return pytime_from_double(tp, d, round, unit_to_ns); } - else { - long long sec = PyLong_AsLongLong(obj); - if (sec == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) { - pytime_overflow(); - } - return -1; - } - static_assert(sizeof(long long) <= sizeof(PyTime_t), - "PyTime_t is smaller than long long"); - PyTime_t ns = (PyTime_t)sec; - if (pytime_mul(&ns, unit_to_ns) < 0) { + long long sec = PyLong_AsLongLong(obj); + if (sec == -1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) { pytime_overflow(); - return -1; } + else if (PyErr_ExceptionMatches(PyExc_TypeError)) { + PyErr_Format(PyExc_TypeError, + "'%T' object cannot be interpreted as an integer or float", + obj); + } + return -1; + } - *tp = ns; - return 0; + static_assert(sizeof(long long) <= sizeof(PyTime_t), + "PyTime_t is smaller than long long"); + PyTime_t ns = (PyTime_t)sec; + if (pytime_mul(&ns, unit_to_ns) < 0) { + pytime_overflow(); + return -1; } + + *tp = ns; + return 0; }