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

Carl M. Johnson cmjohnson.mailinglist at gmail.com
Thu Jun 2 07:17:58 CEST 2011

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. ;-)

I think the benefit of saving that one line is probably outweighed by the
brittleness that this would create (ie. changing x +=  1 to x = x + 1 could
break code), so I withdraw the proposal, at least for now.

One additional problem that I ran into is this:

>>> def f():
...  nonlocal count
...  return count
SyntaxError: no binding for nonlocal 'count' found

Nonlocal fails at the compilation stage if the variable isn't found. On the
other hand, attribute lookup is delayed until runtime, so if by accident you

def f():
    count = 0
    def g():
        cont += 1 #oops typo.
        return cont
    return g

it's not clear when the function should fail: compile time or runtime.

-- Carl
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110601/56aeb92e/attachment.html>

More information about the Python-ideas mailing list