[Python-ideas] Customizing format()

Nick Coghlan ncoghlan at gmail.com
Wed Mar 18 23:21:09 CET 2009


Terry Reedy wrote:
> Nick Coghlan wrote:
> A new conversion specifier should follow the current pattern and be a
> single letter, such as 'c' for 'custom' or 'd' for dict.

Because those characters already have other meanings in string
formatting dictionary (as do many possible single digit codes). The
suggested name "!conv" was chosen based on the existing localeconv()
function name.

> 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.

I believe you're currently right - I'm not sure how hard it would be to
change it to a two step process (parse the whole string first into an
internal parse tree then go through and format each identified field).

As for why I formatted the example the way I did: the {!conv} isn't all
that interesting, since it just says "I accept a conventions
dictionary". Having it at the front of the format string would give it
to much prominence.

> 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).

Aside from not producing any output, the !conv field would still have to
obey all the rules for field naming/numbering. So if your format string
used explicit numbering instead of auto-numbering then the !conv would
need to be explicitly numbered as well.

I agree that having "format fields which are not format fields" isn't
ideal, but the alternative is likely to be something like
yet-another-string-formatting-method which accepts a positional only
conventions dictionary as its first argument.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list