Skip to content

Commit 3ea9ba6

Browse files
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 97e9cfa) Co-authored-by: Mark Dickinson <[email protected]>
1 parent 731732a commit 3ea9ba6

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
@@ -138,6 +138,10 @@ def check(s):
138138
check('123\xbd')
139139
check(' 123 456 ')
140140
check(b' 123 456 ')
141+
# all whitespace (cf. https://github.com/python/cpython/issues/95605)
142+
check('')
143+
check(' ')
144+
check('\t \n')
141145

142146
# non-ascii digits (error came from non-digit '!')
143147
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
@@ -162,11 +162,18 @@ float_from_string_inner(const char *s, Py_ssize_t len, void *obj)
162162
double x;
163163
const char *end;
164164
const char *last = s + len;
165-
/* strip space */
165+
/* strip leading whitespace */
166166
while (s < last && Py_ISSPACE(*s)) {
167167
s++;
168168
}
169+
if (s == last) {
170+
PyErr_Format(PyExc_ValueError,
171+
"could not convert string to float: "
172+
"%R", obj);
173+
return NULL;
174+
}
169175

176+
/* strip trailing whitespace */
170177
while (s < last - 1 && Py_ISSPACE(last[-1])) {
171178
last--;
172179
}

0 commit comments

Comments
 (0)