[Python-ideas] Improved exception messages
Thomas Nyberg
tomuxiong at gmx.com
Tue Jun 6 16:26:29 EDT 2017
I think this diff is probably the correct solution. Basically it just
checks if there's anything left after spaces are stripped and then
throws an error if not:
(By the way sorry for not being clearer in my other message. This diff
is against the current 3.7 master branch. I didn't look at the original
2.7 because I wanted to check that it wasn't fixed in a future version
(which apparently it isn't).)
---------------------
$ git diff
diff --git a/Objects/floatobject.c b/Objects/floatobject.c
index 8c4fe74..c1886cc 100644
--- a/Objects/floatobject.c
+++ b/Objects/floatobject.c
@@ -144,7 +144,13 @@ float_from_string_inner(const char *s, Py_ssize_t
len, void *obj)
while (s < last - 1 && Py_ISSPACE(last[-1])) {
last--;
}
-
+ /* If nothing is left after stripping spaces, return error. */
+ if (s == last) {
+ PyErr_Format(PyExc_ValueError,
+ "could not convert string to float: "
+ "%R", obj);
+ return NULL;
+ }
/* We don't care about overflow or underflow. If the platform
* supports them, infinities and signed zeroes (on underflow) are
* fine. */
---------------------
I just compiled and tested it and it seems to do what we want:
>>> float(" ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: ' '
>>> float(" ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: ' '
>>> float("a")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a'
>>> float("a ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a '
>>> float(" a ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: ' a '
>>> float(" 1 ")
1.0
Cheers,
Thomas
More information about the Python-ideas
mailing list