Sat Apr 30 2022·2 min read
Photo by Lucija Ros
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
Here is an example of how the error occurs.
name = 'Alice' def example(): # ⛔️ UnboundLocalError: local variable 'name' referenced before assignment print(name) name = 'Bob' example()
We assign a value to the
name variable in the function.
namevariable local to the function, and the local
namevariable shadows the one in the global scope.
To solve the error, mark the variable as
global in your function definition.
name = 'Alice' def example(): # 👇️ mark global global name print(name) name = 'Bob' example() # 👉️ 'Alice' example() # 👉️ 'Bob'
If a variable is assigned a value in a function's body, it is a local variable
unless explicitly declared as
Note that you could reference the global
name variable from inside the
function, but if you assign a value to the variable in the function's body, the
local variable shadows the global one.
name = 'Alice' def example(): # ✅ this is ok print(name) example() # 👉️ 'Alice'
If you have a nested function and are trying to assign a value to the local
variables from the outer function, use the
def outer(): # 👇️ initialize message variable message = '' def inner(): # 👇️ Mark message as nonlocal nonlocal message message = 'hello world' print(message) inner() print(message) # 👉️ "hello world" outer()
nonlocal keyword allows us to work with the local variables of enclosing
messagevariable in the
outerfunction, but we were able to change its value in the
Had we not used the
nonlocal statement, the call to the
would have returned an empty string.
def outer(): # 👇️ initialize message variable message = '' def inner(): # 👇️ declares message in inner's scope message = 'hello world' print(message) inner() print(message) # 👉️ "" outer()
An alternative solution to using the
global keyword is to return a value from
the function and use the value to reassign the global variable.
name = 'Alice' def example(): print(name) # 👉️ 'Alice' new_name = 'Bob' return new_name result = example() print(result) # 👉️ 'Bob' name = result print(name) # 👉️ 'Bob'
We simply return the value that we eventually use to assign to the
You should also consider passing the global variable as an argument to the function.
name = 'Alice' def example(first): full_name = first + ' Smith' return full_name result = example(name) print(result) # 👉️ 'Alice Smith'
We passed the
name global variable as an argument to the function.
If we assign a value to a variable in a function, the variable is assumed to be
local unless explicitly declared as