[Python-checkins] gh-95605: Fix `float(s)` error message when `s` contains only whitespace (GH-95665) (GH-95858)
mdickinson
webhook-mailer at python.org
Thu Aug 11 12:17:23 EDT 2022
https://github.com/python/cpython/commit/3ea9ba647850442ade8aec2c84c7f20afd0fb7c4
commit: 3ea9ba647850442ade8aec2c84c7f20afd0fb7c4
branch: 3.11
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: mdickinson <dickinsm at gmail.com>
date: 2022-08-11T17:16:53+01:00
summary:
gh-95605: Fix `float(s)` error message when `s` contains only whitespace (GH-95665) (GH-95858)
This PR fixes the error message from float(s) in the case where s contains only whitespace.
(cherry picked from commit 97e9cfa75a80b54a0630b7371f35e368a12749d1)
Co-authored-by: Mark Dickinson <dickinsm at gmail.com>
files:
A Misc/NEWS.d/next/Core and Builtins/2022-08-04-18-46-54.gh-issue-95605.FbpCoG.rst
M Lib/test/test_float.py
M Objects/floatobject.c
diff --git a/Lib/test/test_float.py b/Lib/test/test_float.py
index e99250199975..304388e1f78c 100644
--- a/Lib/test/test_float.py
+++ b/Lib/test/test_float.py
@@ -138,6 +138,10 @@ def check(s):
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
index 000000000000..49441c6b3118
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2022-08-04-18-46-54.gh-issue-95605.FbpCoG.rst
@@ -0,0 +1,2 @@
+Fix misleading contents of error message when converting an all-whitespace
+string to :class:`float`.
diff --git a/Objects/floatobject.c b/Objects/floatobject.c
index 47d308b8eb37..be6024659ab8 100644
--- a/Objects/floatobject.c
+++ b/Objects/floatobject.c
@@ -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--;
}
More information about the Python-checkins
mailing list