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

Paul Moore p.f.moore at gmail.com
Thu Oct 1 15:11:27 CEST 2009

2009/10/1 Vinay Sajip <vinay_sajip at yahoo.co.uk>:
> If any module wants to use {} formatting for their logging, they can add the
> line
> from logging import BraceMessage as __
> I've used two underscores, since _ might be being used for gettext, but
> obviously the importer can use whatever name they want.
> and then they can use
> logger.debug(__("The {0} is {1}", "answer", 42))
> which I think is more readable than putting in ".format" following the string
> literal. It's not a *huge* point, perhaps, but "Readability counts".
> This has the side benefit that if e.g. Barry wanted to use string.Template for
> formatting, he's just got to replace the above import with something like
> from logging import DollarMessage as __
> Another "working title", please note. And while I've shown these classes being
> imported from logging, it doesn't make sense to put them there if this idea
> were to fly in a more general context. Then, perhaps string would be a better
> home for these classes.

This seems to me to be almost the same as the previous suggestion of
having a string subclass:

class BraceFormatter(str):
    def __mod__(self, other):
        # Needs more magic here to cope with dict argument
        return self.format(*other)

__ = BraceFormatter

logger.debug(__("The {0} is {1}"), "answer", 42)

The only real differences are

1. The positioning of the closing parenthesis
2. The internal implementation of logger.debug needs to preserve
string subclasses properly

But the benefit is that the approach allows anyone to use brace
formatting in any API that currently accepts % format (assuming string
subclasses don't get mangled).

On the one hand, I'd prefer a more general solution. On the other, I'm
nervous about that "assuming string subclasses..." proviso.

I've no real answer, just offering the point up for consideration.


More information about the Python-Dev mailing list