alexgolec
alexgolec

Reputation: 28252

Why do python exceptions typically not print offending values?

For instance, consider the case:

>>> a = []
>>> a[12]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

the exception does not print the value that was out of range.

My guess is that we don't know if the __str__ function of whatever was passed in raises an exception, so we don't touch it?

Upvotes: 12

Views: 241

Answers (2)

aquavitae
aquavitae

Reputation: 19154

Knowing the __str__ method isn't an issue - if it's not supplied for an object, __repr__ is used instead, and an any case __repr__ would usually make more sense in an exception message. As for the reason, I don't think there is a specific reason. If you were to propose changing that and submitted a patch I see no reason offhand why it would be rejected. However, actually making the change would probably be quite a massive effort because it would mean changing wherever the exception is raised. That's actually probably the main reason it hasn't been done. If there is a python developer around, they might be able to give a better answer...

Edit: Its worth pointing out that this is not the case for all exceptions. AttributeError, for example, does report the offending values.

Upvotes: 2

Ethan Furman
Ethan Furman

Reputation: 69110

The value could be printed, it just isn't.

However, there is a tb module on PyPI that actually will print the values of the variables in the stack trace.

Upvotes: 3

Related Questions