[Python-ideas] Improved exception messages

Chris Angelico rosuav at gmail.com
Tue Jun 6 15:51:55 EDT 2017


A question came up on python-list regarding the message given when you
call float(""). It's somewhat unclear due to the way humans tend to
ignore a lack of content:

>>> float("spam")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'spam'
>>> float("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:

Firstly, is there a reason for the empty string to not be surrounded
with quotes? The source code, AIUI, is this:

    x = PyOS_string_to_double(s, (char **)&end, NULL);
    if (end != last) {
        PyErr_Format(PyExc_ValueError,
                     "could not convert string to float: "
                     "%R", obj);
        return NULL;
    }

which, by my reading, should always be repr'ing the string.

Secondly, the actual feature suggestion/request: Incorporate the
original string in the exception's arguments. That way, if there's any
confusion, e.args[1] is the safest way to check what string was
actually being floated.

Feasible? Useful?

ChrisA


More information about the Python-ideas mailing list