Python 101 - annoying UnboundLocalError

timtsoitt

timtsoitt

Posted on April 10, 2022

Python 101 - annoying UnboundLocalError

UnboundLocalError is an error you must have encountered when you learn Python. Let us try to understand this error.

Starting Point

This code snippet can run. Although we do not assign variable x inside inner_function(), it searches variable x from enclosed scope, which is simple_function().

def simple_function():
    x = 10

    def inner_function():
        return x

    return inner_function()


print(simple_function()) # 10
Enter fullscreen mode Exit fullscreen mode

Now we try do assignment to variable x. This time we face UnboundLocalError. Why is that?

# Unable to run
def simple_function():
    x = 10

    def inner_function():
        x = x + 10
        return x

    return inner_function()


print(simple_function()) # UnboundLocalError: local variable 'x' referenced before assignment
Enter fullscreen mode Exit fullscreen mode

When we do an assignment to a variable, this variable is treated as local variable to that scope. Python will shadow any variable in outer scope. For example, it will not care variable x in the simple_function.

When Python interprets the part x + 10, it tries to reference variable x, and then add value 10 to it. However, it does not know where the variable x is in local scope, i.e. the inner_function block. So Python prompts the UnboundLocalError error.

Solution

If you want to reference variable x from the simple_function scope, you need to use the nonlocal keyword.

The nonlocal keyword means the variables are neither global nor local to the function. It instructs Python to look for the variables in outer scope, the simple_function block in our case.

def simple_function():
    x = 10

    def inner_function():
        nonlocal x
        x = x + 10
        return x

    return inner_function()


print(simple_function()) # 20
Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
timtsoitt
timtsoitt

Posted on April 10, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related