diff options
author | Thomas Wouters <thomas@python.org> | 2006-04-11 23:50:33 (GMT) |
---|---|---|
committer | Thomas Wouters <thomas@python.org> | 2006-04-11 23:50:33 (GMT) |
commit | 9cb28bea04066b6b47f84662e1db130eda137b09 (patch) | |
tree | 59dc255307ada1e7e4ce5a80a10d59baaa90f6be /Objects/intobject.c | |
parent | 502348d010be73a20cd5d6ce5512746198baa711 (diff) | |
download | cpython-9cb28bea04066b6b47f84662e1db130eda137b09.zip cpython-9cb28bea04066b6b47f84662e1db130eda137b09.tar.gz cpython-9cb28bea04066b6b47f84662e1db130eda137b09.tar.bz2 |
Fix int() and long() to repr() their argument when formatting the exception,
to avoid confusing situations like:
>>> int("")
ValueError: invalid literal for int():
>>> int("2\n\n2")
ValueError: invalid literal for int(): 2
2
Also report the base used, to avoid:
ValueError: invalid literal for int(): 2
They now report:
>>> int("")
ValueError: invalid literal for int() with base 10: ''
>>> int("2\n\n2")
ValueError: invalid literal for int() with base 10: '2\n\n2'
>>> int("2", 2)
ValueError: invalid literal for int() with base 2: '2'
(Reporting the base could be avoided when base is 10, which is the default,
but hrm.) Another effect of these changes is that the errormessage can be
longer; before, it was cut off at about 250 characters. Now, it can be up to
four times as long, as the unrepr'ed string is cut off at 200 characters,
instead.
No tests were added or changed, since testing for exact errormsgs is (pardon
the pun) somewhat errorprone, and I consider not testing the exact text
preferable. The actually changed code is tested frequent enough in the
test_builtin test as it is (120 runs for each of ints and longs.)
Diffstat (limited to 'Objects/intobject.c')
-rw-r--r-- | Objects/intobject.c | 18 |
1 files changed, 14 insertions, 4 deletions
diff --git a/Objects/intobject.c b/Objects/intobject.c index e3af063..63034bc 100644 --- a/Objects/intobject.c +++ b/Objects/intobject.c @@ -335,7 +335,8 @@ PyInt_FromString(char *s, char **pend, int base) { char *end; long x; - char buffer[256]; /* For errors */ + Py_ssize_t slen; + PyObject *sobj, *srepr; if ((base != 0 && base < 2) || base > 36) { PyErr_SetString(PyExc_ValueError, @@ -359,9 +360,18 @@ PyInt_FromString(char *s, char **pend, int base) end++; if (*end != '\0') { bad: - PyOS_snprintf(buffer, sizeof(buffer), - "invalid literal for int(): %.200s", s); - PyErr_SetString(PyExc_ValueError, buffer); + slen = strlen(s) < 200 ? strlen(s) : 200; + sobj = PyString_FromStringAndSize(s, slen); + if (sobj == NULL) + return NULL; + srepr = PyObject_Repr(sobj); + Py_DECREF(sobj); + if (srepr == NULL) + return NULL; + PyErr_Format(PyExc_ValueError, + "invalid literal for int() with base %d: %s", + base, PyString_AS_STRING(srepr)); + Py_DECREF(srepr); return NULL; } else if (errno != 0) |