Python - Scope
Overview
Estimated time: 20–30 minutes
Understand how Python resolves names using the LEGB rule and how to use global
and nonlocal
sparingly.
Learning Objectives
- Explain the LEGB rule (Local, Enclosing, Global, Built-in).
- Use
nonlocal
for closures andglobal
when necessary. - Avoid namespace collisions and prefer explicit arguments.
Prerequisites
LEGB and closures
def outer():
x = 10
def inner():
return x # from enclosing scope
return inner
fn = outer()
print(fn()) # 10
Using nonlocal
def counter():
count = 0
def inc():
nonlocal count
count += 1
return count
return inc
c = counter()
print(c(), c(), c())
Using global
total = 0
def add(n: int) -> None:
global total
total += n
add(5)
print(total)
Common Pitfalls
- Overusing
global
: prefer passing values and returning results. - Shadowing built-ins: avoid names like
list
,dict
,str
.
Checks for Understanding
- What does LEGB stand for?
- When is
nonlocal
appropriate?
Show answers
- Local, Enclosing, Global, Built-in.
- To mutate a variable in an enclosing (but not global) scope from an inner function.
Exercises
- Write a closure-based accumulator using
nonlocal
. - Refactor a function that uses
global
to accept parameters and return values.