f-string error message
Rob Cliffe
rob.cliffe at btinternet.com
Sun Aug 27 17:19:02 EDT 2023
I am currently using Python 3.11.4.
First I want to say: f-strings are great! I use them all the time,
mostly but by no means exclusively for debug messages. And in 3.12 they
will get even better.
And the improved error messages in Python (since 3.9) are great too!
Keep up the good work.
However the following error message confused me for a while when it
happened in real code:
>>> import decimal
>>> x=42
>>> f"{x:3d}"
' 42'
>>> x=decimal.Decimal('42')
>>> f"{x:3d}"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid format string
I understand that this is an error: I'm telling the f-string to expect
an integer when in fact I'm giving it a Decimal.
And indeed f"{x:3}" gives ' 42' whether x is an int or a Decimal.
However, to my mind it is not the format string that is invalid, but the
value supplied to it.
Would it be possible to have a different error message, something like
ValueError: int expected in format string but decimal.Decimal found
Or am I missing something?
Best wishes
Rob Cliffe
More information about the Python-list
mailing list