[Python-ideas] Added a function to parse str.format() mini-language specifiers
Terry Reedy
tjreedy at udel.edu
Mon Mar 16 21:08:33 CET 2009
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.
>
> The primary use case is for non-builtin numeric types that want to add
> __format__, and want it to support the same mini-language that the built
> in types support. For example see issue 2110, where Mark Dickinson
> implements his own version for Decimal, and suggests it be moved elsewhere.
>
> This function exists in Objects/stringlib/formatter.h, and will just
> need to be exposed to Python code. I propose a function that takes a
> single str (or unicode) and returns a named tuple with the appropriate
> values filled in.
>
> 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
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.
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.
> where would it go? I could expose it through the string module, which
is where the sort-of-related
> Formatter class lives.
That seems the most obvious place.
>
> It could be a method on str and unicode, but I'm not sure that's most
> appropriate.
Terry Jan Reedy
More information about the Python-ideas
mailing list