[Python-Dev] PEP 203 Augmented Assignment
Guido van Rossum
guido@beopen.com
Fri, 04 Aug 2000 10:26:45 -0500
[Thomas]
> The question is in what order the expression
>
> x += y
>
> is evaluated.
>
> x = y
>
> evaluates 'y' first, then 'x', but
>
> x + y
>
> evaluates 'x' first, and then 'y'.
>
> x = x + y
>
> Would thus evaluate 'x', then 'y', and then 'x' (for storing the result.)
> (The problem isn't with single-variable expressions like these examples, of
> course, but with expressions with sideeffects.)
Yes. And note that the Python reference manual specifies the
execution order (or at least tries to) -- I figured that in a
user-friendly interpreted language, predictability is more important
than some optimizer being able to speed your code up a tiny bit by
rearranging evaluation order.
> I think it makes sense to make '+=' like '+', in that it evaluates the lhs
> first. However, '+=' is as much '=' as it is '+', so it also makes sense to
> evaluate the rhs first. There are plenty of arguments both ways, and both
> sides of my brain have been beating eachother with spiked clubs for the
> better part of a day now ;) On the other hand, how important is this issue ?
> Does Python say anything about the order of argument evaluation ? Does it
> need to ?
I say that in x += y, x should be evaluated before y.
> After making up your mind about the above issue, there's another problem,
> and that's the generated bytecode.
[...]
> A lot shorter, and it only needs ROT_FOUR, not ROT_FIVE. An alternative
> solution is to drop ROT_FOUR too, and instead use a DUP_TOPX argument-opcode
> that duplicates the top 'x' items:
Sure.
> However, one part of me is still yelling that '+=' should evaluate its
> arguments like '=', not '+'. Which part should I lobotomize ? :)
That part. If you see x+=y as shorthand for x=x+y, x gets evaluated
before y anyway! We're saving the second evaluation of x, not the
first one!
--Guido van Rossum (home page: http://www.pythonlabs.com/~guido/)