
On Fri, Apr 23, 2021 at 7:24 PM Stephen J. Turnbull <turnbull.stephen.fw@u.tsukuba.ac.jp> wrote:
Serhiy Storchaka writes:
Currently format strings (and f-string expressions) support three conversions: !s -- str, !r -- repr and !a for ascii.
It's not clear to me what these are good for, to be honest. Why not just have s, r, and a format codes? The !conversions don't compose with format codes:
>>> f"{10!r:g}" Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Unknown format code 'g' for object of type 'str'
They do, but they're applied in sequence. After !r, you're dealing with a string, not an integer.
f"{2/3!r:8.6s}" '0.6666 '
So I don't think I want to go further. I have some sympathy for your proposal, in part because I'd like to see something done about moving I18N into the format() mechanism. But I'm going to play devil's advocate, mostly because I'm getting old enough to not like change so much. ;-)
How would that work? I18n needs to work with the whole string, not a single value, as format() does. Or if you mean the str.format() method, that's already an i18n target.
I propose to add support of additional conversions: for int, float and operator.index. It will help to convert automatically printf- like format strings to f-string expressions: %d, %i, %u -- use int, %f -- use float, %o, %x -- use operator.index.
This makes more sense to me than !s, !r, and !a -- you might or might not want these conversions, I guess. But it seems like a lot of complexity to add. On the other hand, isn't the answer "fix __format__ in class definitions?"
For example, currently
>>> for i in "befgodxs": ... print(format(10, i)) ... 1010 1.000000e+01 10.000000 10 12 10 a Traceback (most recent call last): File "<stdin>", line 2, in <module> ValueError: Unknown format code 's' for object of type 'int'
But we could change int.__format__ to allow 's' as a format code[1], automagically calling str(), just as 'efg' are allowed and automagically call float().
Are you asking for every single __format__ function to be required to support specific format codes, or will format() itself handle those? Currently, format codes are handled by the type, but the bang conversions are handled by the f-string itself. ChrisA