Referencing local variable before assignment results in unexpected behavior

Some info for the Python perspective.

The global keyword allows changing the value of global variables from within a function.

X = 1
def f():
    global X
    X = 2

f()
assert X == 2

global works only on module-scoped variables, not on variables defined in an enclosing function.

PEP 3104, created in 2006 and implemented in Python 3.0, introduced the nonlocal keyword, which allows changing the value of a variable defined in enclosing scope from within an inner function.

def f():
    x = 1
    def g():
        nonlocal x
        x = 2
    g()
    return x

assert f() == 2

Before that, an inner function could refer to variables in an enclosing function

def f():
    x = 1
    y = 10

    def g():
        x = 2
        return x + y

    z = g()
    return x, y, z


assert f() == (1, 10, 12)

but there was no way to change them.

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

f() # UnboundLocalError: local variable 'x' referenced before assignment
5 Likes