UnboundLocalError in Python: Why it Occurs and How to Fix it

QASource Engineering Team | October 14, 2024

UnboundLocalError in Python

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.

Disclaimer

This publication is for informational purposes only, and nothing contained in it should be considered legal advice. We expressly disclaim any warranty or responsibility for damages arising out of this information and encourage you to consult with legal counsel regarding your specific needs. We do not undertake any duty to update previously posted materials.

Post a Comment

Categories