[Tutor] a little loop

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri May 31 00:35:22 CEST 2013


On 30 May 2013 21:35, eryksun <eryksun at gmail.com> wrote:
> In terms of sequence methods, it's inplace concatenation. On their
> own, immutable string types only support regular concatenation, but
> the interpreter can evaluate the concatenation inplace for special
> cases. Specifically, it can resize the target string in an INPLACE_ADD
> if it's not interned and has only *one* reference.

It's also for BINARY_ADD in the form a = a + b:

$ python
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = 'abcdefgh' * 128
>>> id_s = id(s)
>>> s = s + 'spam'
>>> print(id(s) == id_s)
True

A rare case of me actually using the dis module:

>>> def f():
...   s = s + 'spam'
...
>>> import dis
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (s)
              3 LOAD_CONST               1 ('spam')
              6 BINARY_ADD
              7 STORE_FAST               0 (s)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE


Oscar


More information about the Tutor mailing list