Why not just show the out-of-range index?
BJörn Lindqvist
bjourne at gmail.com
Mon Dec 4 14:48:18 EST 2006
On 12/4/06, "Martin v. Löwis" <martin at v.loewis.de> wrote:
> Russ schrieb:
> > I love Python, but every time I get an out-of-range error message, I
> > wonder why it didn't just tell me what the out-of-range index was and
> > what the allowable range was. Certainly that information must be
> > available to the exception handler, or how would it know that it is out
> > of range?
>
> Yes, that is true. The information is readily available.
>
> It's not true that it is "trivial" to fix, though: for every fix, there
> ought to be a new test case also, and you have to run the test suite.
> Depending on how fast a developer is, it may take between 30min and
> 1hour to get a fix implemented (for the list case alone, not counting
> all the other sequences).
Maybe it is not as trivial as the OP thought, but it can't be that
hard. It could be implemented as a utility function that does the
index checking:
bool
PyObject_IsIndexOutOfBounds(PyObject *o, const char *ob_name, int i)
{
if (i < 0 || i >= o->ob_size)
{
char buf[256];
const char fmt[] = "%s index %d not in range(%d)"
snprintf(buf, fmt, ob_name, i, o->ob_size);
PyErr_SetString(PyExc_IndexError, buf);
return true;
}
return false;
}
Then replace all code like:
if (i < 0 || i >= a->ob_size) {
PyErr_SetString(PyExc_IndexError, "string index out of range");
return NULL;
}
with:
if (PyObject_IsOutOfBounds((PyObject *)a, "string", i)
return NULL;
Or maybe add "index" and "length" attributes to the PyExc_IndexError?
"index" and "length" would of course be the invalid index and "length"
the length of the container. That would be harder and probably involve
some API change or something.
Sorry I haven't thought this through 100%, but I don't see how
actually _implementing it_ (getting it through the layers of
bureaucracy may be harder) could be so difficult.
> Even though I could fix it, I don't feel tempted to do so: I never had
> this problem; in most cases of IndexError, it was very clear what the
> problem was so I didn't need the additional information.
For you yes, for a newbie the extra information would certainly be helpful.
--
mvh Björn
More information about the Python-list
mailing list