[Python-ideas] Arguments to exceptions

Nick Coghlan ncoghlan at gmail.com
Sun Jul 16 00:18:40 EDT 2017


On 16 July 2017 at 10:12, Jeff Walker <jeff.walker00 at yandex.com> wrote:
> Sorry Stephen (and Steven). I'll do better next time.
>
> The way I see it there are two problems, and the second causes the first.
>
> The first problem is that there is no direct access to the components that make up the error in some of the standard Python exceptions.
>
>     >>> foo
>     Traceback (most recent call last):
>         File "<stdin>", line 1, in <module>
>     NameError: name 'foo' is not defined
>
> If you need access to the name, you must de-construct the error message. To get direct access to the name, it would need to be passed to the exception when raised. Why wasn't that done?

Ease of implementation mainly, as PyErr_Format is currently the
simplest general purpose mechanism for raising informative exceptions
from the C code:
https://docs.python.org/3/c-api/exceptions.html#c.PyErr_Format

All the more structured ones currently require expanding the C API to
cover creating particular exception types with particular field values
(the various PyErr_Set* functions listed on that page).

That does prompt a thought, though: what if there was an f-string
style "PyErr_SetStructured" API, where instead of writing
'PyErr_Format(PyExc_NameError, "name '%.200s' is not defined",
name);', you could instead write 'PyErr_SetStructured(PyExc_NameError,
"name '{name:.200s}' is not defined", name);', and that effectively
translated to setting a NameError exception with that message *and*
setting its "name" attribute appropriately.

The key benefit such a switch to f-string style formatting would
provide is the ability to optionally *name* the fields in the
exception message if they correspond to an instance attribute on the
exception being raised.

Actually implementing such an API wouldn't be easy by any means (and
I'm not volunteering to do it myself), but it *would* address the main
practical barrier to making structured exceptions more pervasive in
the reference interpreter.

Cheers,
Nick.

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


More information about the Python-ideas mailing list