Lesson 21 / 47

Scope & Closures

local, global, nonlocal — and functions that remember their environment.

LEGB scope rule

Python looks up names using the LEGB rule: Local, Enclosing, Global, Built-in — in that order.

global & nonlocal

global and nonlocal let an inner function modify a variable from an outer scope instead of shadowing it.

def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

counter = make_counter()
print(counter())  # 1
print(counter())  # 2

What is a closure?

make_counter above is a closureincrement "closes over" count and keeps its own private copy alive between calls.