]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-95605: Fix `float(s)` error message when `s` contains only whitespace (GH-95665)
authorMark Dickinson <dickinsm@gmail.com>
Wed, 10 Aug 2022 18:25:39 +0000 (19:25 +0100)
committerGitHub <noreply@github.com>
Wed, 10 Aug 2022 18:25:39 +0000 (19:25 +0100)
This PR fixes the error message from float(s) in the case where s contains only whitespace.

Lib/test/test_float.py
Misc/NEWS.d/next/Core and Builtins/2022-08-04-18-46-54.gh-issue-95605.FbpCoG.rst [new file with mode: 0644]
Objects/floatobject.c

index b5e271abc86a5ec5b1a0a2741ec39db3cd43182c..f8350c1e4caa27c682e3e7db4af7c4f39f6f8e0b 100644 (file)
@@ -137,6 +137,10 @@ class GeneralFloatCases(unittest.TestCase):
         check('123\xbd')
         check('  123 456  ')
         check(b'  123 456  ')
+        # all whitespace (cf. https://github.com/python/cpython/issues/95605)
+        check('')
+        check(' ')
+        check('\t \n')
 
         # non-ascii digits (error came from non-digit '!')
         check('\u0663\u0661\u0664!')
diff --git a/Misc/NEWS.d/next/Core and Builtins/2022-08-04-18-46-54.gh-issue-95605.FbpCoG.rst b/Misc/NEWS.d/next/Core and Builtins/2022-08-04-18-46-54.gh-issue-95605.FbpCoG.rst
new file mode 100644 (file)
index 0000000..49441c6
--- /dev/null
@@ -0,0 +1,2 @@
+Fix misleading contents of error message when converting an all-whitespace
+string to :class:`float`.
index 4b1b24f2e702a471becec5a9621ac00ff3d68b28..c4353572d32d8e2d671596aad2e226179f76ac8b 100644 (file)
@@ -162,11 +162,18 @@ float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
     double x;
     const char *end;
     const char *last = s + len;
-    /* strip space */
+    /* strip leading whitespace */
     while (s < last && Py_ISSPACE(*s)) {
         s++;
     }
+    if (s == last) {
+        PyErr_Format(PyExc_ValueError,
+                     "could not convert string to float: "
+                     "%R", obj);
+        return NULL;
+    }
 
+    /* strip trailing whitespace */
     while (s < last - 1 && Py_ISSPACE(last[-1])) {
         last--;
     }