[Python] Closures and Unbound LocalError: local variable'x' referenced before assignment

This article is based on the results of Python 3.7.6.

To make a closure in Python, I wrote code like this:

def f():
    x = 0
    def g():
        x += 1
    g()

f()

The function g refers to the variable x defined within the scope of the function f and is trying to add 1 to it. Doing this will result in an error at x + = 1.

UnboundLocalError: local variable 'x' referenced before assignment

It says that the local variable x was referenced before the assignment. This is because we have created another new variable in g instead of referencing x in f. The above code can be rewritten separately for convenience of declaration and assignment as follows. It uses var as a pseudo syntax for variable declaration.

#note:var is not the correct Python grammar. See above
def f():
    var x           #local variable of f'x'Declare
    x = 0           #Substitute 0 for x
    def g():        #Define the internal function g of f
        var x       #local variable of g'x'Declare
                    #It happens that f also has a variable with the same name, but a different variable
        x += 1      #Add 1 to x(x = x +Syntactic sugar of 1)
                    #Attempts to refer to the value before addition, but an error because it has not been assigned yet
    g()

To express the original intention, write as follows.

def f():
    x = 0
    def g():
        nonlocal x   ## (*)
        x += 1
    g()

Add nonlocal, like(*). This will look for the x defined in the scope one outside (one outside of g = f).

Recommended Posts

[Python] Closures and Unbound LocalError: local variable'x' referenced before assignment
Python> link> 2D array initialization and assignment