Skip to content
Justice Tech School

Scope and the LEGB Rule

Python looks for a name in this order: Local (inside the function), Enclosing (outer functions), Global (the file) and Built-in. This is the LEGB rule. A nested function can read the variables of its outer function, and nonlocal lets it change them.

Example
x = "global"

def outer():
    x = "enclosing"
    def inner():
        print(x)
    inner()

outer()
print(x)

def counter():
    n = 0
    def add():
        nonlocal n
        n += 1
        return n
    return add

c = counter()
print(c(), c())

Result

enclosing
global
1 2

Exercise

Change a variable of the enclosing function.

def add():
     n
    n += 1

Quiz Test

What does the L in LEGB stand for?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.