Lingua-e
← Errors
Python

UnboundLocalError: What It Means and How to Fix It

Error reference

UnboundLocalError

Language

Python

Severity

Medium

When it happens

UnboundLocalError is a subclass of NameError raised when a local variable is referenced before it has been assigned a value.

Potential fixes

Declare the variable with global (for module-level) or nonlocal (for enclosing function scope) before modifying it. Alternatively, pass the value as a parameter and return the new value instead of mutating outer state.

Related errors

Deep dive

UnboundLocalError is a subclass of NameError raised when a local variable is referenced before it has been assigned a value. Python determines variable scope at compile time: if a name is assigned anywhere in a function, it is treated as local throughout that function.

Why it happens

  • A variable is assigned inside a function but read before the assignment line is reached.
  • An augmented assignment (+=, -=) on a name that exists in the enclosing scope but not locally.
  • A conditional branch assigns the variable only sometimes, but it is read unconditionally.
  • Using the same name for both a local variable and a parameter in a confusing way.

Potential fixes

Declare the variable with global (for module-level) or nonlocal (for enclosing function scope) before modifying it. Alternatively, pass the value as a parameter and return the new value instead of mutating outer state.

Examples

Python

Code that triggers the error

count = 0

def increment():
    count += 1  # reads count before assigning

increment()

Error output

UnboundLocalError: local variable 'count' referenced before assignment

Fixed code

count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # 1

Practice in English

How would you explain an UnboundLocalError to a fellow dev? Choose the right phrase:

"I hit an error...

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free