What is Python's LEGB scope rule?medium

Type
conceptual
Topic
scope
Frequency
common
Tags
scope, LEGB, closures
Answer

Python resolves names by searching Local → Enclosing → Global → Built-in scopes in that order, stopping at the first match.

Explanation

Local is the current function's namespace. Enclosing covers outer functions in nested definitions. Global is the module level. Built-in is Python's built-in namespace (len, print, etc.). The lookup happens at runtime, not when the function is defined — which is what makes the late-binding closure trap possible.

Follow-upWhat keywords let you write to an outer scope instead of creating a new local variable?