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

Vinay Sajip vinay_sajip at yahoo.co.uk
Thu Oct 1 15:29:29 CEST 2009


Paul Moore <p.f.moore <at> gmail.com> writes:

> 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
> 

The other difference is that my suggestion supports Barry's desire to use
string.Template with no muss, no fuss ;-) Plus, very little additional work is
required compared to your items 1 and 2. ISTM BraceMessage would be something
like this,

clsss BraceMessage:
    def __init__(self, fmt, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)


Regards,

Vinay



More information about the Python-Dev mailing list