New Python 3.0 string formatting - really necessary?

Duncan Booth duncan.booth at invalid.invalid
Sun Dec 21 16:30:34 CET 2008


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

>> 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).
> 
> That's only plausible if the operations are associative. Addition is 
> associative, but string interpolation is not:

Addition is not associative on arbitrary types.

> 
>>>> "%%%s" % ("%s" % "b")
> '%b'
>>>> ("%%%s" % "%s") % "b"
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: not all arguments converted during string formatting
> 
> Since string interpolation isn't associative, your hypothetical
> __mod__ method might take multiple arguments, but it would have to
> deal with them two at a time, unlike concatenation where the compiler
> could do them all at once. So whether __mod__ takes two arguments or
> many is irrelevant: its implementation must rely on some other
> function which takes two arguments and must succeed or fail on that.

I don't see that. What I suggested was that a % b % c would map to 
a.__mod__(b,c). (a % b) % c would also map to that, but a % (b % c) could 
only possibly map to a.__mod__(b.__mod__(c))




More information about the Python-list mailing list