Augument assignment versus regular assignment

Terry Reedy tjreedy at udel.edu
Mon Jul 10 12:34:53 EDT 2006


"Antoon Pardon" <apardon at forel.vub.ac.be> wrote in message 
news:slrneb4l7c.rg3.apardon at rcpc42.vub.ac.be...
> I disagree. The += version only evaluates the index once, but still has
> to find the object twice.

No it does not *have* to find the object twice and no it does *not* find 
the object twice.  From the viewpoint of the interpreter, the purpose of 
abbreviating 'objectexpression = objectexpression op arg' as 
'objectexpression op=arg' is to avoid unnecessary recalculation

> But as far as I can interpret what is happening from the printed lines

Your print get/set examples from your black-box testing miss the following 
key point.  While the interpreter still has to *use* the object(s) twice, 
once to get and once to set, it no longer has to *calculate* the objects 
twice.  If we open the box and look at the compiled pycode, we get, for 
example:

>>> dis(compile('x[i][j+k]=x[i][j+k]+1', '', 'single'))
  1           0 LOAD_NAME                0 (x)
              3 LOAD_NAME                1 (i)
              6 BINARY_SUBSCR
              7 LOAD_NAME                2 (j)
             10 LOAD_NAME                3 (k)
             13 BINARY_ADD

             14 BINARY_SUBSCR
             15 LOAD_CONST               0 (1)
             18 BINARY_ADD

             19 LOAD_NAME                0 (x)
             22 LOAD_NAME                1 (i)
             25 BINARY_SUBSCR
             26 LOAD_NAME                2 (j)
             29 LOAD_NAME                3 (k)
             32 BINARY_ADD

             33 STORE_SUBSCR

>>> dis(compile('x[i][j+k]+=1', '', 'single'))
  1           0 LOAD_NAME                0 (x)
              3 LOAD_NAME                1 (i)
              6 BINARY_SUBSCR
              7 LOAD_NAME                2 (j)
             10 LOAD_NAME                3 (k)
             13 BINARY_ADD

             14 DUP_TOPX                 2

             17 BINARY_SUBSCR
             18 LOAD_CONST               0 (1)
             21 INPLACE_ADD

             22 ROT_THREE

             23 STORE_SUBSCR

[blank lines added for clarity]

Both forms call binary_subscr to get the number to add to 1 and both call 
store_subscr to set the result back in the list.  But in the first case, 
the expressions for both the source-target list and the index of the value 
for the addition are duplicated and re-evaluated.  In the second, the 
*results* of the first evaluation are duplicated (on the stack) and saved 
for the storage operation.

For understanding the detailed operation of CPython, dis is a great help

Terry Jan Reedy






More information about the Python-list mailing list