Lesson

Python Scope

10 min reading
Free Course

Python Scope: The LEGB Rule, Closures, and nonlocal

Python variable scope decides which regions of your program can read or modify a name. Whenever you reference a variable, Python searches four nested levels in exact order: Local, Enclosing, Global, and Built-in (the LEGB rule).

Understanding scope stops confusing bugs like UnboundLocalError and shows why functions stay safer when they take inputs as arguments rather than mutating globals.

The LEGB Lookup Hierarchy

flowchart TD
    L["1. Local (current function)"] --> E["2. Enclosing (outer function)"]
    E --> G["3. Global (module top level)"]
    G --> B["4. Built-in (len, print, int)"]

If Python finds the name in Local scope, it stops searching immediately. A closure happens when an inner function remembers variables from its Enclosing scope even after the outer function returns.

tax_rate = 0.08  # Global scope

def make_counter(start: int = 0):
    count = start  # Enclosing scope

    def step() -> int:
        nonlocal count
        count += 1
        return count

    return step

counter = make_counter(10)
print(counter(), counter())  # 11 12

global vs nonlocal

nonlocal lets a nested function rebind a variable in its enclosing function, while global lets a function rebind a module-level variable. Avoid global in production code; pass parameters and return values instead.

Common Mistakes to Avoid

  • Triggering UnboundLocalError: Assigning x = x + 1 inside a function without global or nonlocal makes Python treat x as local before it exists.
  • Shadowing built-in names: Assigning list = [1, 2] hides Python's built-in list() everywhere in that scope.
  • Expecting if or for blocks to create a new scope: Only functions, classes, and modules create scopes in Python; loop variables remain visible after a for loop ends.

Frequently Asked Questions

Do if statements or for loops create local scopes in Python?

No. A variable assigned inside an if block or for loop belongs to the surrounding function or module scope.

When is a closure useful in Python?

Closures work cleanly for decorators, factory functions, and lightweight stateful callbacks where writing a full class feels heavy.

How can I inspect variables in local or global scope?

Call locals() inside a function or globals() at module level to see a dictionary of bound names.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Python Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum