[Python-ideas] Why does += trigger UnboundLocalError?

Bruce Leban bruce at leapyear.org
Wed Jun 1 19:32:49 CEST 2011


On Wed, Jun 1, 2011 at 9:56 AM, Ethan Furman <ethan at stoneleaf.us> wrote:

>
> Several times in that thread it was stated that
>
> --> a += 1
>
> is a shortcut for
>
> --> a.__iadd__(1)
>
> It seems to me that this is an implementation detail, and that the actual
> "longcut" is
>
> --> a = a + 1
>
> ...
>
> ~Ethan~
>

a += 1 is not a shortcut for a.__iadd__(1). It's a shortcut for a =
a.__iadd(1). Otherwise this wouldn't work:

>>> x = (1,)
>>> x += (2,)
>>> x
(1, 2)

Note the difference between these two is one opcode:

>>> def f(x,y):
x += y
 >>> dis.dis(f)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                1 (y)
              6 *INPLACE_ADD*
              7 STORE_FAST               0 (x)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE
>>> def g(x,y):
 x = x + y

>>> dis.dis(g)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                1 (y)
              6 *BINARY_ADD*
              7 STORE_FAST               0 (x)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

--- Bruce
Follow me: http://www.twitter.com/Vroo http://www.vroospeak.com
Latest tweet: SO disappointed end of the world didn't happen AGAIN!
#y2k<http://twitter.com/#!/search?q=%23y2k>
 #rapture <http://twitter.com/#!/search?q=%23rapture> Now waiting for 2038!
#unixrapture <http://twitter.com/#!/search?q=%23unixrapture>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110601/878e89ae/attachment.html>


More information about the Python-ideas mailing list