How to Fix: NameError: free variable ‘x’ referenced before assignment in enclosing scope

3D visualization of a robot inside nested boxes confused between an outer variable and a local variable, representing a Python NameError.

Encountering a NameError related to a free variable can be quite daunting. This is a scarier version of the <a href="https://pythonprohub.com/python-errors/unboundlocalerror-local-variable-referenced-before-assignment/">UnboundLocalError</a> we saw earlier. It happens specifically when dealing with nested functions (a function inside another function).

The Scenario

You have an outer function with a variable, and an inner function tries to change it.

Problem Code:

def outer():
    x = 10
    
    def inner():
        # We try to change 'x' from the outer scope
        x += 1 
        print(x)
        
    inner()

outer()
# CRASH! NameError: free variable 'x' referenced before assignment...

The Fix: nonlocal

Just like we used global to fix scope issues at the top level, we use nonlocal to fix them in nested functions. It tells Python: “I don’t want a new local variable; I want the one from the outer (non-global) scope.”

def outer():
    x = 10
    
    def inner():
        nonlocal x  # <--- The magic fix
        x += 1
        print(x)
        
    inner()

outer()
# Output: 11 (Success!)

Similar Posts

Leave a Reply