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

Brett Cannon brett at python.org
Fri Oct 2 01:39:49 CEST 2009

On Thu, Oct 1, 2009 at 14:54, Nick Coghlan <ncoghlan at gmail.com> wrote:
> Vinay Sajip wrote:
>> So there's no need to change modules like logging to explicitly
>> provide support for {}-formatting? What's not to like? ;-) Something
>> like this perhaps should have been added in at the same time as
>> str.format went in.
> I believe classes like fmt_braces/fmt_dollar/fmt_percent will be part of
> a solution, but they aren't a complete solution on their own.

I agree. I view them more as a band-aid over APIs that only accept %
formatting but the user of the library wants to use {} formatting.

> (Naming
> the three major string formatting techniques by the key symbols involved
> is a really good idea though)
> The two major problems with them:
> 1. It's easy to inadvertently convert them back to normal strings. If a
> formatting API even calls "str" on the format string then we end up with
> a problem (and switching to containment instead of inheritance doesn't
> really help, since all objects implement __str__).

Well, you can override the methods on str to always return the proper
thing, e.g. ``def __str__(self): return self``. Do the same for
__add__() and all other methods on strings that return a string
themselves. It should be possible to prevent Python code from
stripping off the class.

> 2. They don't help with APIs that expect a percent-formatted string and
> do more with it than just pass it to str.__mod__ (e.g. inspecting it for
> particular values such as '%(asctime)s')

Nope, they don't and people would need to be warned against this.

> Still, it's worth considering adding the three fmt_* classes to the
> string module to see how far they can get us in adapting the formats for
> different APIs.
> Note that I don't think these concepts are fully baked yet, so we
> shouldn't do anything in a hurry - and anything that does happen should
> be via a PEP so we can flush out more issues.

Having a PEP that lays out how we think people should consider
transitioning their code would be good.


More information about the Python-Dev mailing list