Why does this UnboundLocalError occur (closure)?

closures, global-variables, python, scope

Solution

Python doesn't have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.[1] Thus, the line

counter += 1

implicitly makes `counter` local to `increment()`. Trying to execute this line, though, will try to read the value of the local variable `counter` before it is assigned, resulting in an `UnboundLocalError`.[2]

If `counter` is a global variable, the `global` keyword will help. If `increment()` is a local function and `counter` a local variable, you can use `nonlocal` in Python 3.x.

Problem

What am I doing wrong here? ``` counter = 0 def increment(): counter += 1 increment() ``` The above code throws an `UnboundLocalError`.

Original source

Related problems