[Python-ideas] Globalize lonely augmented assignment

Georg Brandl g.brandl at gmx.net
Sat Jun 12 20:28:03 CEST 2010


Am 12.06.2010 17:43, schrieb Bruce Frederiksen:

> So we are considering the case where no assignment to the variable
> exists within the function, but there is an augmented assignment.  But
> in this case, if we say that the variable is a local variable, how did
> this local variable get a value that the augmented assignment can then
> use?
> 
> The only way that I can think of is:
> 
> def foo():
>     def bar():
>         nonlocal A
>         A = []
>     bar()
>     A += [2]

(I assume you intended a global A somewhere outside of foo().)
With the proposed semantics, this would actually be a compilation error,
since there is no nonlocal binding of A that the "nonlocal" statement
could bring into scope.

> What am I missing?

Currently, augmented assignment has a very straightforward translation to
plain assignment::

   a += b   is equivalent to
   a = a.__iadd__(b)

(Not just ``a.__iadd__(b)``, as some people think at first.  That's a
problem, see below.)

With the proposal, it would be much more complicated and dependent on
the context: "... it's the same as <code>, but if the name would only
be made a local by augmented assignment statements, it's automatically
made nonlocal if there's a matching non-local binding, or global
otherwise."  Pretty scary.  And while I think about it, it's pretty
implicit as well, since it basically makes a global or nonlocal binding
(this would be different if the translation didn't include the actual
assignment).

Georg

-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.




More information about the Python-ideas mailing list