Fixing Python UnboundLocalError: Local Variable ‘x’ Accessed Before Assignment

Updated: December 31, 2023 By: Guest Contributor Post a comment

Understanding UnboundLocalError

The UnboundLocalError in Python occurs when a function tries to access a local variable before it has been assigned a value. Variables in Python have scope that defines their level of visibility throughout the code: global scope, local scope, and nonlocal (in nested functions) scope. This error typically surfaces when using a variable that has not been initialized in the current function’s scope or when an attempt is made to modify a global variable without proper declaration.

Solutions for the Problem

To fix an UnboundLocalError, you need to identify the scope of the problematic variable and ensure it is correctly used within that scope.

Method 1: Initializing the Variable

Make sure to initialize the variable within the function before using it. This is often the simplest fix.

Method 2: Using Global Variables

If you intend to use a global variable and modify its value within a function, you must declare it as global before you use it.

Method 3: Using Nonlocal Variables

If the variable is defined in an outer function and you want to modify it within a nested function, use the nonlocal keyword.

Examples

# Example: Fixing UnboundLocalError by initializing the variable

def my_function():
    x = 10  # Initialize x within the function
    print(x)

my_function()

# Example: Correct use of a global variable
x = 10

def my_function():
    global x  # Declare x as global
    x += 5
    print(x)

my_function()
print(x)

# Example: Correct use of nonlocal variable

def outer_function():
    x = 10
    def inner_function():
        nonlocal x  # Declare x as nonlocal
        x += 5
        print(x)
    inner_function()
    print(x)

outer_function()

That’s it. Happy coding!