Skip to content

Commit b4f968e

Browse files
gh-95605: Fix float(s) error message when s contains only whitespace (GH-95665) (GH-95859)
This PR fixes the error message from float(s) in the case where s contains only whitespace. (cherry picked from commit 97e9cfa) Co-authored-by: Mark Dickinson <[email protected]>
1 parent 346aa78 commit b4f968e

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

Lib/test/test_float.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,10 @@ def check(s):
135135
check('123\xbd')
136136
check(' 123 456 ')
137137
check(b' 123 456 ')
138+
# all whitespace (cf. https://github.com/python/cpython/issues/95605)
139+
check('')
140+
check(' ')
141+
check('\t \n')
138142

139143
# non-ascii digits (error came from non-digit '!')
140144
check('\u0663\u0661\u0664!')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix misleading contents of error message when converting an all-whitespace
2+
string to :class:`float`.

Objects/floatobject.c

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,11 +150,18 @@ float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
150150
double x;
151151
const char *end;
152152
const char *last = s + len;
153-
/* strip space */
153+
/* strip leading whitespace */
154154
while (s < last && Py_ISSPACE(*s)) {
155155
s++;
156156
}
157+
if (s == last) {
158+
PyErr_Format(PyExc_ValueError,
159+
"could not convert string to float: "
160+
"%R", obj);
161+
return NULL;
162+
}
157163

164+
/* strip trailing whitespace */
158165
while (s < last - 1 && Py_ISSPACE(last[-1])) {
159166
last--;
160167
}

0 commit comments

Comments
 (0)