Skip to content

UnboundLocalError

LeCarbonator edited this page Oct 22, 2022 · 4 revisions

This error commonly occurs when you work with a global scoped variable in a function. You may use global variables in functions, but if you reassign it in the same function AFTER using it, you will cause an error because it assumes you're working with function scoped variables.

Example 1

This is working as intended

x = 5
def func():
    print(x) #prints 5
func()

This also works, but it will print 10.

x = 5
def func():
     x = 10
+    print(x) #prints 10
func()

This causes an error

x = 5
def func():
     # Which variable are you referencing here?
-    print(x)
-    x = 10
func()

Example 2

Variables that are defined only when a condition is met also cause this error. If that condition fails, you cannot interact with the variable. Note that this still has to be within a function to raise this error.

x = 5
def func():
    if x == 5:     # evaluates to True
        list = []
    print(list)    # list has been defined
    list.append(x)

func()
x = 6
def func():
    if x == 5:     # evaluates to False
        list = []
-   print(list)    # list has not been defined. UnboundLocalError!
-   list.append(x)

func()
Clone this wiki locally