New Python 3.0 string formatting - really necessary?

Duncan Booth duncan.booth at invalid.invalid
Sun Dec 21 13:45:32 CET 2008


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:

> Errors should never pass silently, unless explicitly silenced. You
> have implicitly silenced the TypeError you get from not having enough 
> arguments for the first format operation. That means that you will 
> introduce ambiguity and bugs.
> 
> "%i %i %i %i" % 5 % 3 %7
> 
> Here I have four slots and only three numbers. Which output did I
> expect? 
> 
> '%i 5 3 7'
> '5 %i 3 7'
> '5 3 %i 7'
> '5 3 7 %i'
> 
> Or more likely, the three numbers is a mistake, there is supposed to
> be a fourth number there somewhere, only now instead of the error
> being caught immediately, it won't be discovered until much later.
> 
You seem to have made an unwarranted assumption, namely that a binary 
operator has to compile to a function with two operands. There is no 
particular reason why this has to always be the case: for example, I 
believe that C# when given several strings to add together optimises this 
into a single call to a concatenation method.

Python *could* do something similar if the appropriate opcodes/methods 
supported more than two arguments:

a+b+c+d might execute a.__add__(b,c,d) allowing more efficient string 
concatenations or matrix operations, and a%b%c%d might execute as 
a.__mod__(b,c,d).

In that alternate universe your example:

    	"%i %i %i %i" % 5 % 3 %7

simply throws "TypeError: not enough arguments for format string", and

      "%s" % (1,2,3)

just converts the tuple as a single argument. It also provides the answer 
to how you put a percent in the format string (double it) and what happens 
if a substitution inserts a percent (it doesn't interact with the 
formatting operators).



More information about the Python-list mailing list