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

"Martin v. Löwis" martin at v.loewis.de
Wed Sep 30 05:15:49 CEST 2009


Steven Bethard wrote:
> There's a lot of code already out there (in the standard library and
> other places) that uses %-style formatting, when in Python 3.0 we
> should be encouraging {}-style formatting. 

I don't agree that we should do that. I see nothing wrong with using
% substitution.

> We should really provide some sort of transition plan.

-1.

> Consider an example from the logging
> docs:
> 
> logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
> 
> We'd like to support both this style as well as the following style:
> 
> logging.Formatter()

Now, that's different. IIUC, you are not actually performing the
substitution here, but only at a later place.

So changing to the new formatting mechanism is an API change.
I agree that the new placeholder syntax needs to be supported.

> * Add a new class, NewFormatter, which uses the {}-style formatting.
> This is ugly because it makes the formatting we're trying to encourage
> look like the alternative implementation instead of the standard one.

It's also ugly because the class has the word "new" in its name, which
no class should ever have. In a few years, it would still be around,
but not new anymore.

> * Have Formatter convert all %-style formatting strings to {}-style
> formatting strings (automatically). This still involves some guessing,
> and involves some serious hacking to translate from one to the other
> (maybe it wouldn't even always be possible?). But at least we'd only
> be using {}-style formatting under the hood.

I don't see the point of having a converter. The tricky part, as you
say, is the guessing. Whether the implementation then converts the
string or has two alternative formatting algorithms is an implementation
detail. I would favor continued use of the actual % substitution
code.

I would propose that the format argument gets an argument name,
according to the syntax it is written in. For PEP 3101 format,
I would call the argument "format" (like the method name of the
string type), i.e.

logging.Formatter(
  format="{asctime} - {name} - {levelname} - {message}")

For the % formatting, I suggest "dicttemplate" (assuming that
you *have* to use dictionary %(key)s style currently).

The positional parameter would also mean dicttemplate, and
would be deprecated (eventually requiring a keyword-only
parameter).

Regards,
Martin




More information about the Python-Dev mailing list