[Python-Dev] bpo-34595: How to format a type name?
encukou at gmail.com
Tue Sep 11 20:54:22 EDT 2018
On 09/11/18 15:23, Victor Stinner wrote:
> Last week, I opened an issue to propose to add a new %T formatter to
> PyUnicode_FromFormatV() and so indirectly to PyUnicode_FromFormat()
> and PyErr_Format():
> I merged my change, but then Serhiy Storchaka asked if we can add
> something to get the "fully qualified name" (FQN) of a type, ex
> "datetime.timedelta" (FQN) vs "timedelta" (what I call "short" name).
> I proposed a second pull request to add %t (short) in addition to %T
> But then Petr Viktorin asked me to open a thread on python-dev to get
> a wider discussion. So here I am.
After a discussion with Victor. I'll summarize where we are now.
There are actually two inconsistencies to fix:
- Python modules use `type(obj).__name__` and C extensions use
`Py_TYPE(obj)->tp_name`, which inconsistent.
- Usage __name__ or __qualname__, and prepending __module__ or not, is
inconsistent across types/modules.
It turns out that today, when you want to print out a type name, you
nearly always want the fully qualified name (including the module unless
it's "builtins"). So we can just have "%T" and not "%t". (Or we can add
"%t" if a use case arises).
It should be possible to do this also in Python, preferably using a name
similar to "%T".
Most of the usage is in error messages and __repr__, where we don't need
to worry about compatibility too much.
It should be possible to get the name if you have the type object, but
not an instance of it. So, the proposed `PyUnicode_FromFormat("%T",
obj)` is incomplete -- if we go that way, we'll also need a function
like PyType_GetFullName. Making "%T" work on the type, e.g.
`PyUnicode_FromFormat("%T", Py_TYPE(obj))`, would be more general.
So, I propose adding a "%T" formatter to PyUnicode_FromFormat, to be
used like this:
and a "T" format code for type.__format__, to be used like this:
More information about the Python-Dev