This local variable may be used before it is defined. If a variable is assigned to in a function and not explicitly declared global or nonlocal then it is assumed to be a local variable. If it is used before it is defined then an UnboundLocalError will be raised.

Review the code and consider the intended scope of the variable. Determine whether the variable should be global or local in scope. If a global variable is required then add a global statement, or in Python 3 you can use a nonlocal statement if the variable occurs in an enclosing function. Otherwise, ensure that the variable is defined before it is used.

The following code includes different functions that use variables. test1() fails with an UnboundLocalError because the local variable var is used before it is initialized.

  • Python Standard Library: Built-in Exceptions: UnboundLocalError.
  • Python Frequently Asked Questions: Why am I getting an UnboundLocalError when the variable has a value?.
  • Python Course: Global and Local Variables.
  • Python Language Reference: The global statement, The nonlocal statement.