[issue18163] Add a 'key' attribute to KeyError

Stéphane Blondon report at bugs.python.org
Fri Feb 12 18:10:10 EST 2021


Stéphane Blondon <stephane.blondon at gmail.com> added the comment:

I'm interested by such feature.

I see examples of versions of the message provided by KeyError:
- sometimes with a message (for example `PyErr_SetString(PyExc_KeyError, "name too long");` at [1])
- sometimes with the missing key (for example `PyErr_SetObject(PyExc_KeyError, key);` at [2])

It explains why there is a difference in the messages in KeyError (as said in previous messages).

PyErr_SetString(), PyErr_Format(), PyErr_FormatV() (implemented in Python/errors.c) don't have a parameter to set the missing key. So I think it would be easier to set the missing attribute before calling thoses functions.


According to [3], the C PyExc_KeyError matches the Python KeyError exception.

So I think to:
- Add a 'missing_key' attribute to KeyError_str (in [4])
- Add the missing key to PyExc_KeyError instance before the call of PyErr_SetString(), PyErr_SetObject(), etc.

Do you think such strategy is doable?
What do you think about it? Is it the way you think about it? If not, do you have some hint?


I already made some minor patches to cpython but only in the Python part, never in C one.


1: https://github.com/python/cpython/blob/master/Modules/unicodedata.c#L1398
2: https://github.com/python/cpython/blob/master/Python/hamt.c#L2767
3: https://docs.python.org/3/c-api/exceptions.html?highlight=pyerr_format#standard-exceptions
4: https://github.com/python/cpython/blob/master/Objects/exceptions.c#L1569

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue18163>
_______________________________________


More information about the Python-bugs-list mailing list