[Python-ideas] Customizing format()

Terry Reedy tjreedy at udel.edu
Wed Mar 18 21:33:49 CET 2009

Nick Coghlan wrote:
> Eric Smith wrote:

>> I agree: I like it, but it's not enough. I use str.format() way more
>> often than I hope to ever use builtin format(). If we make any change,
>> I'd rather see it focused on the format mini-language.
> Perhaps we could add a new ! type to the formatting language that allows
> the developer to mark a particular argument as the conventions
> dictionary? Then you could do something like:
> # DE and US dicts as per Raymond's format() example
> fmt = "The value is {:,.5f}{!conv}"

A new conversion specifier should follow the current pattern and be a 
single letter, such as 'c' for 'custom' or 'd' for dict.

If, as I would expect, str.format scans left to right and interprets and 
replaces each field spec as it goes, then the above would not work. So 
put the conversion field before the fields it applies to.

This, of course, makes string formatting stateful.  With a 'shift lock' 
field added, an 'unshift' field should also be added.  This, though, has 
the problem that a blank 'field-name' will in 3.1 either be 
auto-numbered or flagged as an error (if there are other explicitly 
numbered fields).

I am a little uneasy about 'replacement fields' that are not really 
replacement fields.

> fmt.format(num, DE)
> fmt.format(num, US)
> fmt.format(num, dict(thousands_sep='''))
> As with !a and !s, you could use any normal field specifier to select
> the conventions dictionary. Obviously, the formatting arguments would be
> ignored for that particular field.

Terry Jan Reedy

More information about the Python-ideas mailing list