[Python-ideas] Added a function to parse str.format() mini-language specifiers

Terry Reedy tjreedy at udel.edu
Mon Mar 16 23:09:47 CET 2009

Eric Smith wrote:
> Terry Reedy wrote:
>> Eric Smith wrote:
>>> I'd like to add a function (or method) to parse str.format()'s 
>>> standard mini-language format specifiers. It's hard to get right, and 
>>> if PEP 378 is accepted, it gets more complex.
> ...
>>> So, is such a function desirable, and if so,
>> Yes, but I would take it further and and consider the string and 
>> dict/named-tuple as alternate interfaces to the formatting machinery. 
>> So I would
> If the only use case for this is for non-builtin numeric types, I'd vote 
> for a named tuple. But since Mark (who's one of the primary users) also 
> raised the dict issue, I'll give it some thought.
>> a) add an inverse function that would take a dict or named tuple and 
>> produce the field specifier as a string (or raise ValueError).  Such a 
>> string could be embedded into a complete format string.  Some people 
>> might prefer this specification method.
> This is a pretty simple transformation. I'm not so sure it's all that 
> useful.
>> b> amend built-in format() to take a dict/n-t as the second argument 
>> on the basis that it is silly to transform the parse result back into 
>> a string just to be parsed again.  This would make repeated calls to 
>> format faster by eliminating the parsing step.
> But format() works for any type, including ones that don't understand 
> the standard mini-language. What would they do with this info?

The same thing they would do (whatever that is) if the second argument 
were instead the equivalent unparsed format-spec string.  The easiest 
implementation of what I am proposing would be for the parse_spec 
function whose output you propose to expose were to recognize when its 
input is not a string but previous parse output.  Just as iter(iter(ob)) 
is iter(ob), parse(parse(spec)) should be the same as parse(spec).


More information about the Python-ideas mailing list