UnboundLocalError
PythonERRORNotableName ErrorHIGH confidence

Local variable referenced before assignment

Production Risk

Common beginner mistake; Python compiles variable scope at parse time, not runtime.

What this means

A subclass of NameError raised when a local variable is referenced before being assigned a value. Python determines at compile time that a variable is local (because it is assigned in the function), so any reference before assignment fails.

Why it happens
  1. 1Assigning to a variable in a function while trying to use the outer-scope version before the assignment
  2. 2Conditional assignment where one branch never runs, leaving the variable undefined
  3. 3Augmented assignment (+=) on a variable that does not yet exist in local scope
How to reproduce

A function assigns to a variable in one branch but reads it in another.

trigger — this will error
trigger — this will error
count = 10

def increment():
    count += 1  # Python sees 'count' as local due to assignment
    return count

increment()

expected output

UnboundLocalError: local variable 'count' referenced before assignment

Fix 1

Use the global or nonlocal keyword

WHEN You intend to modify an outer scope variable

Use the global or nonlocal keyword
count = 10

def increment():
    global count
    count += 1
    return count

Why this works

global tells Python to use the module-level variable rather than creating a local one.

Fix 2

Pass the value as a parameter and return it

WHEN Modifying an outer variable (preferred over global)

Pass the value as a parameter and return it
def increment(count):
    return count + 1

count = 10
count = increment(count)

Why this works

Passing values explicitly avoids shared mutable state and makes the function testable.

Code examples
Triggerpython
count = 10
def inc():
    count += 1  # UnboundLocalError: local variable referenced before assignment
inc()
Handle with try/exceptpython
try:
    process()
except UnboundLocalError as e:
    print(f"Variable scope issue: {e}")
Avoid by passing as parameterpython
def inc(count):
    return count + 1

count = 10
count = inc(count)
What not to do

Overuse global variables

Global mutable state makes code hard to test and reason about; prefer parameters and return values.

Sources
Official documentation ↗

Python Docs — Built-in Exceptions

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors