Issue33410
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) * ![]() |
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) * ![]() |
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:00 | admin | set | github: 77591 |
| 2018-05-02 17:06:33 | eric.smith | set | nosy:
+ eric.smith messages: + msg316081 |
| 2018-05-02 14:33:37 | abarry | set | status: open -> closed nosy:
+ abarry resolution: not a bug |
| 2018-05-02 14:22:10 | alexomics | create | |

