
On 25Apr2021 01:01, Chris Angelico <rosuav@gmail.com> wrote:
On Sat, Apr 24, 2021 at 11:36 PM Stephen J. Turnbull <turnbull.stephen.fw@u.tsukuba.ac.jp> wrote:
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.
Now also add in that you will need uppercase and titlecase, and then allow actual formatting of the string as well as case selection.
Yes but those are just red herrings. To me that translates as "you need to provide the conversions you want to support". I suppose a mixin would let me present the suite my application wanted.
Then make sure that every message you format can have every piece of text supporting this, since you'll never know exactly what parts of what messages may need this sort of manipulation. It won't look nearly as simple any more.
That's there the __format__ side caused me trouble - everything wanting ":foo" needs a __format__ method. Whereas "!foo" and an augumentation to str.format_map to add conversions means I don't have to magic the values being used in the format string. See my adjacent much longer post. Maybe I'm trying to say that "!foo" would benefit similar extensibilty as ":foo" already has. The former is for presenting arbitrary values, and the latter is for presenting particular types of values i.e. outside the class vs inside the class. Cheers, Cameron Simpson <cs@cskk.id.au>