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

James Y Knight foom at fuhm.net
Thu Oct 1 17:42:38 CEST 2009


On Oct 1, 2009, at 9:11 AM, Paul Moore wrote:
> 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)


I'd rather make that:

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

__ = BraceFormatter

That is, *not* a string subclass. Then if someone attempts to mangle  
it, or use it for anything but %, it fails loudly.

James


More information about the Python-Dev mailing list