[Python-ideas] Enhance exceptions by attaching some more information to them

Nick Coghlan ncoghlan at gmail.com
Sun Feb 16 02:09:02 CET 2014


On 16 February 2014 01:40, Sebastian Kreft <skreft at gmail.com> wrote:
> More than once I've been in a situation where I wish that some of the stdlib
> exceptions had a better message or some more information to help me diagnose
> the problem.
>
> For example:
> a = [1, 2, 3, 4, 5]
> a[5]
> IndexError: list index out of range
>
> In this case there's no reference to neither the length of the array nor to
> the offending index.
>
> I'm of the idea that we could extend the exceptions by adding some more
> information to them, so 3rd party libraries could use them for
> debugging/logging.

Yes, having particular exceptions expose more structured data would be
a good thing, and some improvements have already been made in that
direction (ImportError now has name and path attributes, for example)

The barriers are largely practical ones rather than philosophical:

1. Each updated exception needs to have the new optional attributes
and keyword-only arguments defined (in C for the building exceptions,
although Argument Clinic makes the argument parsing aspects easier
now), along with appropriate docstring and documentation updates, as
well as changes to the default representation and/or implicit
calculation of an args[0]. (They typically have to be optional keyword
only parameters for backwards compatibility reasons)

2. To actually benefit end users, the new exception capabilities need
to be used appropriately in the core interpreter and standard library.

It's easy to look at the scope of work involved in step 2, and back
away from working on step 1. However, it's important to realise that
step 2 can be done incrementally - step 1 is about making it
*possible* to provide more structured information in the exceptions,
and then step 2 can happen more opportunistically by tackling a
particular part of the interpreter or standard library at a time. (for
example, that is how the improved introspection for builtins and
extension modules is being rolled out).

Step 1 could likely benefit from being elaborated in a PEP, as that
then provides a useful starting point for other implementations when
they go to update their own builtin exception implementations
accordingly.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list