SkillByAIOpen interactive version →

Lesson 21 / 49

Scope & Closures

Understand LEGB scope, the global and nonlocal keywords, and closures 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 closure — increment "closes over" count and keeps its own private copy alive between calls.