Skip to content

KeyError adds quotes to message #138248

@StanFromIreland

Description

@StanFromIreland

Bug description:

In the case of a SyntaxError, the code:

int integer = 0;
PyErr_Format(PyExc_SyntaxError, "text number: %d", integer);

Raises:

SyntaxError: text number: 0

However, with a KeyError:

int integer = 0;
PyErr_Format(PyExc_KeyError, "text number: %d", integer);

Raises:

KeyError: 'text number: 0'

If the message contains single quotes, it nicely raises with double quotes:

KeyError: "text number: '0'"

The same can be achieved with Python:

>>> raise KeyError(f'text number: {1}')
Traceback (most recent call last):
  File "<python-input-4>", line 1, in <module>
    raise KeyError(f'text number: {1}')
KeyError: 'text number: 1'

The documentation does not mention this behavior, the other builtin exceptions do not add them.

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions