Python: Function global and nonlocal variables

By Xah Lee. Date: .

Global keyword

The global keyword tells a function that a variable name refers to a global variable (defined outside any function).

By default, python function only have access to local variables defined in the function body.

x = 3

def ff():
    # declare the x is the global one
    global x
    return x

print(ff())
# 3

Name conflict

when there is already a local name same as global name, it's syntax error

x = 3

# when there is already a local name same as global name, it's syntax error

def ff():
    x = 4
    global x
    return x

# SyntaxError: name 'x' is assigned to before global declaration

Local var name can override global

x = 3

def ff():
    global x
    # local var name can override global
    x = 4
    return x

print(ff())
# 4

nonlocal keyword

The nonlocal keyword tells a function that a variable name refers to a outer variable (defined outside any function) but is not a global variable.

x = 3

def ff():
    x = 4

    def gg():
        # declare the x is the nonlocal one
        nonlocal x
        return x

    return gg()

print(ff())
# 4

print(x)
# 3