On Sun, Aug 27, 2023, at 17:19, Rob Cliffe via Python-list wrote:
> 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?

It's up to the type what format strings are valid for it, so you can't really 
go "int expected". However, a more detailed error string like "invalid format 
string '3d' for object Decimal('42')" might be useful.

right now we have some inconsistencies:
- float object [same for str, int, etc]
ValueError: Unknown format code 'd' for object of type 'float' [if it thinks 
it's identified a single-letter 'code' in the usual microlanguage]
ValueError: Invalid format specifier '???' for object of type '[type]'
- arbitrary object that doesn't override __format__, ipaddress
TypeError: unsupported format string passed to [type].__format__
- datetime, decimal
ValueError: Invalid format string

neither shows the value of the offending object, only its type. incidentally, 
ipaddress and object don't support the usual field width, padding, etc 
specifiers

[int supports code 'f' just fine, by the way, but has the same message as float 
if you give it 's']

Going beyond that, it *might* be viable to have some sort of "guess what 
numeric type the format string was intended for", shared across at least all 
numeric types of objects. Alternatively, we could require all numeric types to 
support all numeric formats, even ones that don't make a lot of sense.
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to