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

Terry Reedy tjreedy at udel.edu
Mon Mar 16 23:19:55 CET 2009


Nick Coghlan wrote:
> Eric Smith wrote:
>> So, is such a function desirable, and if so, where would it go? I could
>> expose it through the string module, which is where the sort-of-related
>> Formatter class lives.
> 
> string.parse_format and string.build_format perhaps? The inverse
> operation would be useful if you just wanted to do something like "use a
> default precision of 3" but otherwise leave things up to the original
> object.
> 
>   def custom_format(fmt, value):
>     details = string.parse_format(fmt)
>     if details["precision"] is None: # Assumes None indicates missing
>       details["precision"] = 3
>     fmt = string.build_format(details)
>     return format(fmt, value)

     return format(value, fmt) # ;-)

> While having to rebuild and reparse the string is a little annoying,

yes

> changing that would involve changing the spec for the __format__ magic
> method and I don't think we want to go there.

If parse_format were idempotent for its output like iter, then the 
change would, I think, be pretty minimal.  I am assuming here that the 
__format__ method calls the parse_format(fmt) function that Eric 
proposed to expose.  If details == parse_format(details) == 
parse_format(build_format(details)), then the rebuild and reparse is not 
needed and passing details instead of the rebuilt string should be 
transparent to __format__.

tjr




More information about the Python-ideas mailing list