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: Incomplete format string syntax for Exceptions
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: eric.smith, thet
Priority: normal Keywords:

Created on 2018-06-12 21:31 by thet, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg319402 - (view) Author: Johannes Raggam (thet) Date: 2018-06-12 21:31
The following is valid Python 2:

>>> 'okay {0:s}'.format(Exception('test'))
'okay test'
>>> 'okay {0}'.format(Exception('test'))
'okay test'

The following fails on Python 3.6:

>>> 'okay {0:s}'.format(Exception('test'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to Exception.__format__

While this doesn't fail:

>>> 'okay {0}'.format(Exception('test'))
'okay test'
msg319408 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2018-06-12 21:59
This is because Exception does not define __format__, so object.__format__ is being called. object.__format__ does not allow any format specifier to be used. You get the same error for any object without its own __format__, when you supply a format spec.

>>> 'okay {0:s}'.format(sys)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to module.__format__

The reason this is enforced is because it allows an Execption.__format__ to be added in the future, without worrying what existing format specifiers are being used. We had a problem adding complex.__format__ because people had supplied format specs when formatting complex numbers, assuming they acted like strings. But now we've prevented this problem from happening in the future.

If you want to provide str formatting options to something like an exception, you should force-convert it to a str first, using !s:

>>> 'okay {0!s:*^10}'.format(Exception('test'))
'okay ***test***'
History
Date User Action Args
2022-04-11 14:59:01adminsetgithub: 78029
2018-06-12 21:59:37eric.smithsetstatus: open -> closed

type: behavior
components: + Interpreter Core, - ctypes

nosy: + eric.smith
messages: + msg319408
resolution: not a bug
stage: resolved
2018-06-12 21:31:51thetcreate