
On Fri, Apr 23, 2021 at 7:26 PM Stephen J. Turnbull <turnbull.stephen.fw@u.tsukuba.ac.jp> wrote:
Cameron Simpson writes:
I would _frequently_ like to be able to provide custom conversions. At present I'm using elaborate hacks based on __getattr__ etc to recognise things like this:
'{x} is {x_lc} in lowercase'
where the _lc suffix is caught and a value computed from "x".
Custom conversions would let me use this:
'{x} is {x!lc} in lowercase'
I don't understand how this is supposed to work. It looks to me like !code is a preprocessor:
>>> print(f'{1!a:g}') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Unknown format code 'g' for object of type 'str'
If so,
'{x} is {x!lc:foo} in lowercase'
will fail because str doesn't implement the 'foo' format code. Do we really need to extend format() rather than using
def lc(x): return str(x).lower()
'{x} is {lc(x)} in lowercase'
That works in an f-string but not in str.format(), so it's not i18n-compatible. I'm sympathetic to the plea for conversions, but I'm not sure that this is the best way to do it. What WOULD work, though, is actual attributes. I'm not sure why x_lc is a thing, but it would certainly work as x.lc - though not as x.lower(), since method calls aren't supported. So the built-in str type still won't work here. ChrisA