
Cameron Simpson writes:
On 23Apr2021 18:25, Stephen J. Turnbull <turnbull.stephen.fw@u.tsukuba.ac.jp> wrote:
I don't understand how this is supposed to work. It looks to me like !code is a preprocessor: [...] If so,
'{x} is {x!lc:foo} in lowercase'
will fail because str doesn't implement the 'foo' format code.
Maybe we're talking about different things. In the example above, I'm talking about "lc", not "foo".
I don't think so. I know you want to talk only about "lc", but I want to understand how this interacts with "foo", and why you can't use "foo" in your application. My basic issue with these proposals is that the existing !conversions are basically syntactic sugar for formats that could have been implemented as format codes. Like the debugging '=' code in f-strings, they are there because they're facilities that are commonly desired by programmers for introspecting the program, regardless of the type of object. I suppose the designers of the feature wanted to avoid *mandating* any interpretation of the format string, though they did provide a standard syntax for convenience. In fact I think that Serhiy's use case (casting numbers to a more appropriate type for the desired format) is more plausible than the !a and !r conversions.
My use case is presupplied strings, eg a command line supplied format string.
In that case the format string is user input, and x is a variable in the program that the user can have substituted into their string? Assuming that *exact* use case, wouldn't >>> class LowerableStr(str): ... def __format__(self, fmt): ... if fmt == 'lc': ... return self.lower() ... else: ... return str.__format__(self, fmt) ... >>> "{x} is {x:lc} in lowercase".format_map({'x' : LowerableStr("This")}) 'This is this in lowercase' do? For generic x you'd have to do something a bit more complicated, but the basic strategy would be the same. Similarly, it shouldn't be hard to design a fairly generic wrapper class that allows you to map format codes to arbitrary functions. Certainly allowing an arbitrary map of preprocessers that can be invoked with "{x!key}" is more aesthetic and elegant in your source. But functionally, it seems to me it's just duplicative of the __format__ mechanism, and so it probably not a great idea. Steve