# Variable Scope & the LEGB Rule

> Master the Python namespace lookup hierarchy: the LEGB rule (Local, Enclosing, Global, Built-in), lexical closures, the global and nonlocal keywords, and diagnosing UnboundLocalError.

Subject: Python | Lesson 11 of 24 | 7 min read
Interactive lesson: https://codewithanimation.in/python/scope
Previous: [Positional, Default & *args / **kwargs](https://codewithanimation.in/python/arguments-kwargs.md) | Next: [Lambda Functions & Higher-Order Pipelines](https://codewithanimation.in/python/lambda-functions.md)

## The LEGB Lookup Rule

A scope is a textual region of a Python program where a namespace is directly accessible. When Python encounters a variable name, it searches four nested namespaces in a strict deterministic order known as the LEGB rule:

1. Local (L): Names assigned or declared inside the current function body.

2. Enclosing (E): Names in the local scope of any enclosing/outer functions (relevant in nested functions and closures), searched from the nearest inner function outward.

3. Global (G): Names assigned at the top-level of the current module file, or declared using `global` inside a function.

4. Built-in (B): Python pre-loaded module (`builtins`) containing built-in functions and exceptions like `len()`, `range()`, `int()`, and `ValueError`.

## Modifying Outer Scopes: global and nonlocal

Reading outer variables happens automatically through the LEGB rule. However, assigning to a variable inside a function creates a new local variable by default, shadowing any identically-named variable in an outer scope.

To modify a module-level variable from inside a function, declare it with the `global` keyword: `global counter`.

In nested functions, to rebind a variable that belongs to an enclosing outer function (without making it global), declare it with the `nonlocal` keyword: `nonlocal counter`. This is foundational for stateful closures.

## Closures and Encapsulated State

A closure occurs when an inner function retains access to variables from its enclosing scope even after the outer function has finished executing and its stack frame has returned.

For example, a generator function `def make_counter(): count = 0; def inc(): nonlocal count; count += 1; return count; return inc` packages the `count` variable inside the returned function's `__closure__` attribute.

Closures provide lightweight data encapsulation without needing to write a full class.

## Common mistake: The Dreaded UnboundLocalError

Consider this common error: `x = 10; def bump(): print(x); x += 1; bump()`.

When Python compiles the body of `bump()`, it inspects all assignments. Because `x += 1` assigns to `x`, Python classifies `x` as a local variable for the entire function body.

When the first line `print(x)` executes, Python looks for `x` exclusively in the local scope. Since no value has been assigned to local `x` yet, Python raises `UnboundLocalError: local variable 'x' referenced before assignment`.

It does not fall back to the global `x = 10`. To fix this, you must either add `global x` at the top of the function or avoid mutating global state altogether.

## Tip: Avoid global Variables in Production

Mutating global variables creates hidden temporal coupling between disparate parts of your application, making unit testing fragile and concurrency prone to race conditions. Instead of modifying globals, pass dependencies in as arguments and return updated values.

## Try it: The LEGB Scope Lookup Radar

Scan outward through Local, Enclosing, Global, and Built-in namespaces. Observe how variable names resolve at each boundary or trigger an UnboundLocalError.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/scope

## Check yourself

### Question 1

In what order does Python search namespaces when looking up an unqualified variable name?

- A. Local -> Enclosing -> Global -> Built-in
- B. Global -> Local -> Enclosing -> Built-in
- C. Built-in -> Global -> Enclosing -> Local
- D. Local -> Global -> Enclosing -> Built-in

Correct answer: A

Python resolves identifiers using the LEGB hierarchy: first Local, then any Enclosing functions, then Global (module), and finally Built-in.

- Why not B: Python always checks the local function frame before looking outward.
- Why not C: Built-in is the final fallback namespace, searched last.
- Why not D: Enclosing scopes in nested functions take precedence over the module's global scope.

### Question 2

What causes `UnboundLocalError: local variable 'count' referenced before assignment`?

- A. A function reads a variable that is assigned anywhere in the same function without a global or nonlocal declaration
- B. The variable was deleted using the del keyword in a separate thread
- C. The variable name contains an illegal character not supported by the tokenizer
- D. The function was called with fewer arguments than specified in the signature

Correct answer: A

If a variable is assigned anywhere inside a function, Python marks it as local for that entire scope. Referencing it before that assignment raises UnboundLocalError.

- Why not B: UnboundLocalError is a single-thread compile-time scoping decision.
- Why not C: Illegal characters trigger a SyntaxError during parsing.
- Why not D: Missing arguments trigger a TypeError.

### Question 3

Which keyword allows an inner nested function to reassign a variable belonging to its immediate outer function?

- A. nonlocal
- B. global
- C. outer
- D. closure

Correct answer: A

The nonlocal keyword binds a name to an enclosing function's namespace, allowing closures to modify outer local state without declaring a global variable.

- Why not B: global targets the top-level module namespace, bypassing enclosing function scopes.
- Why not C: outer is not a keyword in Python.
- Why not D: closure is a computer science term, not a Python keyword.

## Remember this

- Python resolves variable names following the LEGB rule: Local -> Enclosing -> Global -> Built-in.
- Assigning to a variable inside a function automatically makes it local for the entire function body.
- Use nonlocal to rebind variables in an enclosing outer function within a closure.
- UnboundLocalError happens when code reads a variable before assigning to it in a function that contains an assignment to that same name.
