UnboundLocalError: local variable referenced before assignment

The unboundlocalerror: local variable referenced before assignment is raised when you try to use a variable before it has been assigned in the local context. Python doesn't have variable declarations , so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local .

For ex:


Python error local variable referenced before assignment

If you set the value of a variable inside the function , python understands it as creating a local variable with that name. This local variable masks the global variable .

Here, the line

counter += 1

implicitly makes "counter" local to increment(). Trying to execute this line, though, will try to read the value of the local variable "counter" before it is assigned, resulting in an UnboundLocalError . To solve this problem, you can explicitly say it's a global by putting global declaration in you function.


Python unboundlocalerror

The global statement does not have to be at the beginning of the function definition, but that is where it is usually placed. Wherever it is placed, the global declaration makes a variable to global variable everywhere in the function. If increment() is a local function and counter a local variable, you can use "nonlocal" in Python 3.x. This keyword is useful when we need to assign any value to nested scope variable.

Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they're declared global with the global keyword). All variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the global symbol table, and then in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.