/errors/python/unboundlocalerror-cannot-access-local-variable
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
- tool
- Python
- exit code
- 1
- versions
- Python 3.11+ (current message), Python 3.10 and earlier (older wording)
- os
- any
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value means a function reads a local variable before it has been assigned. The usual trigger: the function assigns to a name that also exists as a global (count += 1). Any assignment makes the name local for the whole function body, so the global is no longer visible. Add global count, or better, pass the value in and return the result.
Reproduce it
cat > app.py <<'EOF'
count = 0
def increment():
count += 1
return count
increment()
EOF
python app.pyOutput · exit 1
Traceback (most recent call last):
File "/tmp/work/app.py", line 7, in <module>
increment()
~~~~~~~~~^^
File "/tmp/work/app.py", line 4, in increment
count += 1
^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a valuePython 3.10 and earlier report the same error as local variable 'count' referenced before assignment. Python 3.11 and later use the wording above.
Fixes
python - <<'EOF'
count = 0
def increment_global():
global count # change the module-level variable
count += 1
return count
def increment(value): # preferred: no shared state
return value + 1
def make_counter():
total = 0
def step():
nonlocal total # change the enclosing function's variable
total += 1
return total
return step
print(increment_global(), increment(10))
step = make_counter()
print(step(), step())
EOFOutput
1 11 1 2
The other common form is a conditional assignment: a variable assigned only inside if found: and read after the if. Give it a default value before the branch.