PEP 737: PyUnicode_FromFormat(): Add %T format to format the type name of an object · Issue #111696 · python/cpython (original) (raw)
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 thanPyHeapTypeObject.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
- PEP 737: gh-111696: Add %T format to PyUnicode_FromFormat() #111703
- gh-111696: type(str) returns the fully qualified name #112129
- PEP 737: gh-111696: Add type.__fully_qualified_name__ attribute #112133
- gh-111696, PEP 737: Add PyType_GetFullyQualifiedName() function #116815
- gh-111696, PEP 737: Add PyType_GetModuleName() function #116824
- gh-111696, PEP 737: Add %T and %N to PyUnicode_FromFormat() #116839