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

Nick Coghlan ncoghlan at gmail.com
Mon Mar 16 22:52:26 CET 2009

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

  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)

While having to rebuild and reparse the string is a little annoying,
changing that would involve changing the spec for the __format__ magic
method and I don't think we want to go there.


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

More information about the Python-ideas mailing list