]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-81267: Correct time.sleep() error message (#131055)
authorStan Ulbrych <89152624+StanFromIreland@users.noreply.github.com>
Wed, 12 Mar 2025 08:12:57 +0000 (08:12 +0000)
committerGitHub <noreply@github.com>
Wed, 12 Mar 2025 08:12:57 +0000 (08:12 +0000)
Lib/test/test_time.py
Misc/NEWS.d/next/Library/2025-03-10-20-23-00.gh-issue-81267.a39381.rst [new file with mode: 0644]
Python/pytime.c

index 1147997d8d86bf21c4d09d4e38514e38d5637131..cd6c08f183ff9596a85ff69c98623537ef542a4a 100644 (file)
@@ -167,6 +167,11 @@ class TimeTestCase(unittest.TestCase):
         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 (file)
index 0000000..9c9a86d
--- /dev/null
@@ -0,0 +1,2 @@
+Correct :func:`time.sleep` error message when an object that cannot be interpreted
+as an integer or float is provided.
index b10d5cf927b7e10f0097a7e8dee88811d260015a..2ca92037c2e2f14f46ad5e31c0da10f283c49b41 100644 (file)
@@ -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;
 }