This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Using type in a format with padding causes TypeError
Type: behavior Stage: resolved
Components: Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: abarry, alexomics, eric.smith
Priority: normal Keywords:

Created on 2018-05-02 14:22 by alexomics, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg316072 - (view) Author: Alex (alexomics) Date: 2018-05-02 14:22
When trying to print a type in a formatted string with padding TypeError is raised. See examples below.

These work:
>>> a = 'abc'
>>> print('{a}'.format(a=type(a)))
<class 'str'>
>>> print('{a}'.format(a=str(type(a))))
<class 'str'>

These don't:
>>> print('{a: >10}'.format(a=type(a)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to type.__format__
>>> t = type(a)
>>> print('{a: >10}'.format(a=t))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to type.__format__
msg316074 - (view) Author: Anilyka Barry (abarry) * (Python triager) Date: 2018-05-02 14:33
`type` has a default `__format__` implementation which doesn't accept any formatting options. This is expected behaviour.
msg316081 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2018-05-02 17:06
The problem is that type.__format__ doesn't exist, so object.__format__ is being called, and it throws an error if you provide a format spec. This is done for future expansion: if we do want to add type.__format__ in the future, we don't have to worry about existing cases that are using format specs that might not work with the new type.__format__.

No format spec is the same as calling str() on the argument and returning that, which is what is happening in your working examples.

If you want to apply a str formatting spec, you should covert the argument to a str first, using either !s or str():

>>> print('{a!s: >10}'.format(a=type(a)))
<class 'str'>
>>> print('{a: >10}'.format(a=str(type(a))))
<class 'str'>
History
Date User Action Args
2022-04-11 14:59:00adminsetgithub: 77591
2018-05-02 17:06:33eric.smithsetnosy: + eric.smith
messages: + msg316081
2018-05-02 14:33:37abarrysetstatus: open -> closed

nosy: + abarry
messages: + msg316074

resolution: not a bug
stage: resolved
2018-05-02 14:22:10alexomicscreate