Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't understand why UnboundLocalError occurs (closure) [duplicate]

What am I doing wrong here?

counter = 0  def increment():   counter += 1  increment() 

The above code throws an UnboundLocalError.

like image 224
Randomblue Avatar asked Feb 13 '12 17:02

Randomblue


People also ask

Why am I getting an UnboundLocalError when the variable has a value?

The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. You can solve this error by ensuring that a local variable is declared before you assign it a value.

How do you fix UnboundLocalError in Python?

The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function. To solve the error, mark the variable as global in the function definition, e.g. global my_var .

What are global variables in Python?

Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

How does global work in Python?

In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.


1 Answers

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.

like image 179
Sven Marnach Avatar answered Oct 15 '22 18:10

Sven Marnach