What does UnboundLocalError mean in Python?

Updated October 2026 · How we answer

Short answerUnboundLocalError occurs when a local variable is used before it has been assigned a value. This often happens when a variable is assigned inside a function, making it local, but is referenced before that assignment.

Why UnboundLocalError Happens

In Python, a variable that is assigned anywhere inside a function is considered local to that function unless explicitly declared global or nonlocal. If you try to read that variable before the assignment, Python raises UnboundLocalError because the local name exists but has no value yet.

This is different from NameError, which occurs when a name is not defined at all. UnboundLocalError specifically means the name is recognized as local but is unbound at the time of use.

  • Assigning to a variable anywhere in a function makes it local throughout the function.
  • Referencing it before the assignment triggers the error.
  • Using the same name as a global variable can cause confusion.

Common Scenarios and Fixes

A typical case is when you have a global variable and then assign to it inside a function without declaring it global. Python treats the name as local, so the earlier reference fails.

To fix it, either declare the variable as global (or nonlocal) if you intend to modify the outer variable, or ensure the variable is assigned before any use. Alternatively, restructure the code to avoid the early reference.

  • Use 'global var' inside the function if you want to modify a global variable.
  • Use 'nonlocal var' for variables in enclosing function scopes.
  • Initialize the variable at the start of the function if it's purely local.

Common mistakes

  • Thinking that Python checks the global scope first when a variable is assigned inside a function.
  • Confusing UnboundLocalError with NameError; they have different causes.
  • Assuming that reading a global variable before assigning to it in the same function is allowed.
From our shopsCASEONYX: Dark-luxe tough phone cases.