LEGB Scope
Overview
Variable scope determines where in your code a specific variable is accessible. Python resolves variable names strictly following the LEGB rule: Local -> Enclosing -> Global -> Built-in. When you ask Python for a variable, it checks the current Local function first. If missing, it checks Enclosing functions, then Global module-level variables, and finally the Built-in core Python functions. Understanding LEGB prevents 'variable not defined' and shadowing bugs.
Syntax
x = "Global"
def outer_function():
x = "Enclosing"
def inner_function():
x = "Local"
print(x) # Resolves to "Local" (First level of LEGB)
inner_function()
# --- Modifying Scopes ---
count = 0
def increment():
global count # REQUIRED to modify a Global variable inside a Local scope
count += 1
increment()
print(count) # 1Common Pitfalls
- UnboundLocalError: Attempting to modify a global variable inside a function without first declaring
global var_name. Python assumes any assigned variable is local unless explicitly told otherwise. - Shadowing Built-ins: Naming a variable
list,str,dict, orid. This overwrites the Built-in scope. If you declarelist = [1, 2], callinglist("text")later will crash because the built-in function was destroyed.
Interview Questions
global and nonlocal keywords?global allows a local function to modify a variable sitting at the top module level. nonlocal allows an inner nested function to modify a variable defined in its immediate Enclosing (outer) function.
Real-World Example
Using nonlocal to maintain persistent state inside a closure without needing a Class.
def make_counter():
count = 0
def counter():
nonlocal count # Targets the 'count' in make_counter's scope
count += 1
return count
return counter
my_counter = make_counter()
print(my_counter()) # 1
print(my_counter()) # 2Check Your Knowledge
Test your understanding of LEGB Scope with these quick questions.