[Python-Dev] summary of transitioning from % to {} formatting

MRAB python at mrabarnett.plus.com
Sun Oct 4 02:11:39 CEST 2009

Terry Reedy wrote:
> Steven Bethard wrote:
>> I thought it might be useful for those who don't have time to read a
>> million posts to have a summary of what's happened in the formatting
>> discussion.
> definitely
>> The basic problem is that many APIs in the standard library and
>> elsewhere support only %-formatting and not {}-formatting, e.g.
>> logging.Formatter accepts::
>>   logging.Formatter(fmt="%(asctime)s - %(name)s")
>> but not::
>>   logging.Formatter(fmt="{asctime} - {name}")
>> There seems to be mostly agreement that these APIs should at least
>> support both formatting styles, and a sizable group (including Guido)
>> believe that %-formatting should eventually be phased out (e.g. by
>> Python 4). There are a number of competing proposals on how to allow
>> such APIs to start accepting {}-format strings:
>> * Add a parameter which declares the type of format string::
>>     logging.Formatter(fmt="{asctime} - {name}", format=BRACES)
>>   The API code would then switch between %-format and {}-format
>>   based on the value of that parameter. If %-formatting is to be
>>   deprecated, this could be done by first deprecating
>>   format=PERCENTS and requiring format=BRACES, and then changing the
>>   default to format=BRACES.
> ...
>> * Create translators between %-format and {}-format::
>>     assert to_braces("%(asctime)s") == "{asctime}"
>>     assert to_percents("{asctime}") == "%(asctime)s"
>>   these could then either be used outside of the API::
>>     logging.Formatter(fmt=to_percents("{asctime} - {name}"))
>>   or they could be used within the API combined with some sort of
>>   heuristic for guessing whether a {}-format string or a %-format
>>   string was passed in::
>>     logging.Formatter(fmt="{asctime} - {name}")
> How about combining these two. Add an optional form or style=xxx 
> parameter -- which could also allow DOLLARS for $-formats -- for 
> resolving ambiguities. If not present, make a reasonable guess. IE, if 
> string has no '%' and multiple {} pairs, or no {} pairs and multiple %s, 
> the guess is at least .999 sure. which is to not, not hardly a guess. 
> The extra arg can be supplied if and when needed.
Maybe if the style is a callable then that's the formatting function?
(Or is that asking for trouble? :-))

In that case the style could default to a function which guesses which
style is being used and then the appropriate function.

> The machinery for this should be not be logging specific, so it can be 
> used through throughout the library, and exposed so that others can use it.

More information about the Python-Dev mailing list