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

Nick Coghlan ncoghlan at gmail.com
Thu Jun 2 07:49:58 CEST 2011

On Thu, Jun 2, 2011 at 3:17 PM, Carl M. Johnson
<cmjohnson.mailinglist at gmail.com> wrote:
> On Wed, Jun 1, 2011 at 1:21 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> Currently, the rule is simple: any assignment tells the compiler to treat
>> x as local. If you want nonlocal or global, you have to declare it as such.
>> Nice and simple. What actual real-world problem are you trying to solve that
>> you want to change this behaviour?
> The best counter-arguments I've heard so far are Nick's (it would be a pain
> to go into the guts and change this, and you also need to think about PyPy,
> Jython, IronPy, etc., etc.) and this one.
> In terms of "real world problems" this solves, it makes the solution to the
> Paul Graham language challenge problem (build a function that returns an
> accumulator) one line shorter. Which is a bit silly, but so far as I can
> tell, nonlocal was created just to say we have an answer to the Paul Graham
> question. ;-)

Nah, nonlocal was added because the introduction of decorators
increased the use of closures, and boxing and unboxing variables
manually is a PITA.

Note that the "translation" of 'x += y' to 'x = x + y' is and always
has been a gross oversimplification (albeit a useful one).

Reality is complicated by possible provision of __iadd__ by the
assignment target, as well as the need to pair up
__getitem__/__setitem__ and __getattr__/__setattr__ appropriately when
the target is a subscript operation or attribute access.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list