Topic 59 of 64
Local vs Global Variables
Overview
Python uses LEGB scope resolution: Local → Enclosing → Global → Built-in. Variables in a function are local by default. The 'global' and 'nonlocal' keywords explicitly access outer scopes — understanding this prevents NameError and UnboundLocalError bugs.
Syntax
python
x = 10 # global
def func():
# x here refers to global x (read-only access)
print(x) # 10
def modify():
global x # declare intent to modify global
x = 20
def outer():
y = 5
def inner():
nonlocal y # access enclosing scope
y = 10
inner()
print(y) # 10Common Pitfalls
- UnboundLocalError happens when you read a variable before assigning it in the same function — Python treats it as local due to the assignment below.
- Avoid using 'global' in production code — it creates hidden dependencies. Use function parameters, return values, or class attributes instead.
- Interview tip: LEGB stands for Local, Enclosing, Global, Built-in — Python searches scopes in this order when resolving names.
Real-World Example
Counter using closure with nonlocal
example
python
def make_counter(start: int = 0):
count = start
def increment(by: int = 1) -> int:
nonlocal count
count += by
return count
def reset() -> None:
nonlocal count
count = start
return increment, reset
inc, rst = make_counter(0)
print(inc()) # 1
print(inc(5)) # 6
rst()
print(inc()) # 1