Lesson 69 +10 XP

Scope

Scope

Scope decides which variables a piece of code can see. Python has local, global, and nonlocal scopes.

Local scope

A variable created inside a function is local to it:

def myfunc():
    x = 300  # local
    print(x)

myfunc()      # 300
print(x)      # NameError: x is not defined

Function inside function

A variable in the outer function is visible to the inner one:

def outer():
    x = 300
    def inner():
        print(x)  # can see the outer x
    inner()

outer()  # 300

Global scope

A variable created outside any function is global; everyone can read it:

x = 300  # global

def myfunc():
    print(x)

myfunc()      # 300
print(x)      # 300

The global keyword

To modify a global from inside a function, declare it with global:

def myfunc():
    global x
    x = 500

myfunc()
print(x)  # 500

Without global, the function would create a new local x.

The nonlocal keyword

nonlocal changes a variable in the enclosing (outer) function:

def outer():
    x = 300
    def inner():
        nonlocal x
        x = 200
    inner()
    print(x)  # 200

outer()

Reading order

If a name isn't local, Python looks outward: local, then enclosing, then global, then built-in.

TL;DR

  • Local variables exist only in their function.
  • Global variables are readable everywhere.
  • global modifies a global; nonlocal modifies the enclosing scope.
  • Python searches scopes from inside out.