Software Dev and QA Tips

Python's UnboundLocalError - Why it Occurs and How to Fix it?

Written by QASource Engineering Team | Oct 14, 2024 4:00:00 PM

An UnboundLocalError in Python occurs when you try to reference a local variable before assigning it a value within the function. This happens because Python assumes that any variable assigned within a function is local unless declared otherwise. If a variable is accessed before it’s assigned, Python raises this error.

Example:

def my_function():
    print(query)  # Trying to access 'query' before it is assigned
    query = "Hello"
my_function()

Running the above code will lead to “UnboundLocalError: cannot access local variable 'query' where it is not associated with a value”

Cause of Error: In the above code, Python interprets the query as a local variable because it's assigned later in the function. However, since the query hasn't been assigned a value before the print(query) statement, it throws an error.

How to resolve the error

  1. Assign the variable before accessing it: Ensure the variable is assigned a value before it is used.

    def my_function():
        query = "Hello"  # Assign before using it
        print(query)
    
    my_function()
    
  2. Declare the variable as global: If you intend to use a global variable, declare it global within the function.

    query = "Hello"  # Global variable
    def my_function():
    global query
    print(query)  # Now Python knows to use the global 'query'
    my_function()
    

Key Takeaways

  • UnboundLocalError happens when a local variable is referenced before being assigned.
  • To fix it, ensure the variable is properly initialized before usage and declare it global if needed.