8000 gh-95605: Fix `float(s)` error message when `s` contains only whitesp… · python/cpython@97e9cfa · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 97e9cfa

Browse files
authored
gh-95605: Fix float(s) error message when s contains only whitespace (GH-95665)
This PR fixes the error message from float(s) in the case where s contains only whitespace.
1 parent 37c0f9c commit 97e9cfa

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

141145
# non-ascii digits (error came from non-digit '!')
142146
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)
0