On 2016-11-29 09:43, Brett Cannon wrote:
One way to make this cheap is to have a reasonable default message and use attributes on the exceptions trigger the use of the default message. Nearly a year ago I filed a bunch of issues for ideas on providing attributes on exceptions where it made sense, e.g. an index attribute on IndexError (http://bugs.python.org/issue18162). If we did this then for classes like IndexError there constructor could be `IndexError(index=10, start=0, end=3)` and then __str__() can lazily construct the string representation using a default message, e.g. `"index {} is out of range of{} to {}".format(index, start, end)`. Make the arguments keyword-only and they become backwards-compatible and so the only overhead you pay for these richer messages are keyword-based construction if you simply never access the repr for the exception.
I absolutely think this is the way to go. Having the relevant information (the list that was too short, the index that was too big, the key that wasn't there, etc.) is useful in many situations, and it's much better to have that information in a programmatic form than just squashed into an error message. This then makes it relatively easy to write wrappers that take bubbling-up exceptions and try to construct more detailed messages for a less experienced audience. Right now this is difficult or impossible because the exception objects don't record the information that would be needed for these expanded messages. -- Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown