UnboundLocalError: cannot access local variable
What it means
Inside a function, you read a variable before it was given a value. A name you assign anywhere in a function is local to the whole function, so Python does not fall back to a global variable with the same name. The variable may also be set only on some paths, such as one branch of an if.
1. Changing a global variable inside a function
This raises the error
Traceback (most recent call last): File "<exec>", line 6, in <module> File "<exec>", line 4, in add_one UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
The fix
1
count += 1 assigns to count, which makes it local to the function, so there is nothing to read yet. Passing the value in and returning the result is the clearest fix; writing global count inside the function also works.
2. A variable set only in one branch of an `if`
This raises the error
pass Traceback (most recent call last): File "<exec>", line 7, in <module> File "<exec>", line 4, in grade UnboundLocalError: cannot access local variable 'result' where it is not associated with a value
The fix
pass fail
When score is below 50 the if body never runs, so result is never set. A starting value, or an else, covers every path.
3. A variable set inside a `try` that failed
This raises the error
not a number: abc Traceback (most recent call last): File "<exec>", line 8, in <module> File "<exec>", line 6, in to_number UnboundLocalError: cannot access local variable 'value' where it is not associated with a value
The fix
not a number: abc 0
When int() fails, the assignment never happens. Setting a value in the except block too means the function always has something to return.
When you see this error, check
- Look for an assignment to the same name later in the function, including
+=. - Give the variable a starting value at the top of the function.
- Make sure every
if,else,tryandexceptpath sets it. - Prefer passing values in and returning results over
global.
Related errors
All Python errors · How to read a traceback · Step through your code