Behavior of += (was Re: [Python-Dev] Customization docs)

jepler at unpythonic.net jepler at unpythonic.net
Mon Jun 3 19:06:14 EDT 2002


On Mon, Jun 03, 2002 at 06:32:34PM -0400, John Roth wrote:
[about "x = ('aaa'); x[0] += 'bbb'"]
> Maybe. It might actually update the string, producing
> 'aaabbb' at a different location in memory,
> and then (properly) fail to update the tuple.

There need be no speculate.

>>> import dis
>>> def f(x): x[0] += 'bbb'
... 
>>> dis.dis(f)
          0 SET_LINENO               1

          3 SET_LINENO               1
          6 LOAD_FAST                0 (x)
          9 LOAD_CONST               1 (0)
         12 DUP_TOPX                 2
         15 BINARY_SUBSCR       
         16 LOAD_CONST               2 ('bbb')
         19 INPLACE_ADD         
         20 ROT_THREE           
         21 STORE_SUBSCR        
         22 LOAD_CONST               0 (None)
         25 RETURN_VALUE        
>>> def g(x): x[0] = x[0] + 'bbb'
... 
>>> dis.dis(g)
          0 SET_LINENO               1

          3 SET_LINENO               1
          6 LOAD_FAST                0 (x)
          9 LOAD_CONST               1 (0)
         12 BINARY_SUBSCR       
         13 LOAD_CONST               2 ('bbb')
         16 BINARY_ADD          
         17 LOAD_FAST                0 (x)
         20 LOAD_CONST               1 (0)
         23 STORE_SUBSCR        
         24 LOAD_CONST               0 (None)
         27 RETURN_VALUE        

The differences are that the two LOAD_FAST / LOAD_CONST sequences have been
optimized to LOAD_FAST / LOAD_CONST / DUP_TOPX, a ROT_THREE has been added
to get operands in the right place, and (the real difference) the operation
is INPLACE_ADD instead of BINARY_ADD in the 'meat' of the function.

So, yes, in both questions a string 'aaabbb' will be constructed somewhere
in memory, but only on the stack (cpythonically speaking, of course)

Jeff





More information about the Python-list mailing list