Skip to content

PEP 737: PyUnicode_FromFormat(): Add %T format to format the type name of an object #111696

Closed
@vstinner

Description

@vstinner

It's common to format a type name by accessing PyTypeObject.tp_name member. Example:

PyErr_Format(PyExc_TypeError,
             "__format__ must return a str, not %.200s",
             Py_TYPE(result)->tp_name);

Problems:

  • PyTypeObject.tp_name (type.__name__) is less helpful than PyHeapTypeObject.ht_qualname (type.__qualname__). I would prefer to display the qualified type name.
  • PyTypeObject.tp_name is a UTF-8 encoded string, it requires to decode the UTF-8 string at each call.
  • I would like to remove PyTypeObject members (tp_name) from the public C API: issue C API: Investigate how the PyTypeObject members can be removed from the public C API #105970.
  • By the way, in the early days of Python, PyString_FromFormat() used a buffer with a fixed size, so the output string should be truncated to avoid overflow. But nowadays, PyUnicode_FromFormat() allocates a buffer on the heap and is no longer limited to 200 characters. Truncated a type name can miss important information in the error message. I would prefer to not truncate the type name.

I propose adding a %T format to PyUnicode_FromUnicode() to format the qualified name of an object type. For example, the example would become:

PyErr_Format(PyExc_TypeError,
             "__format__ must return a str, not %T", result);

In 2018, I already added %T format to PyUnicode_FromFormat(): issue GH-78776. See related python-dev discussion. The change was reverted.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions