1. The LEGB Name Resolution Hierarchy
Four Concentric Scoping Environments
- L (Local): Names assigned inside a function body.
- E (Enclosing): Names in the local scope of any enclosing/outer functions (closures).
- G (Global): Names assigned at the top-level of a module file or declared with the `global` keyword.
- B (Built-in): Built-in Python names (print, len, range, ValueError, etc.).
- Python searches in strict order: L -> E -> G -> B. The first scope where the name is found wins.
x = "Global x"
def outer():
x = "Enclosing x"
def inner():
x = "Local x"
print("Resolved:", x)
inner()
outer()