Python Basics — Scope & Closures
1 minute read
Scope & Closures
Understanding scope — where variables live and how long they exist — is essential for writing correct, bug-free Python code. This chapter covers how Python resolves variable names and introduces closures, a powerful pattern that combines functions with their surrounding state.
What You’ll Learn
Quick Preview
# A closure — a function that remembers its enclosing scope
def make_multiplier(factor):
def multiply(number):
return number * factor # factor is "closed over"
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
Why Scope Matters
| Problem |
Caused By |
Solution |
UnboundLocalError |
Assigning to a variable that shadows a global |
Use global keyword or pass as argument |
| Unexpected value changes |
Modifying a global from inside a function |
Avoid mutable globals; pass data explicitly |
| Hard-to-debug code |
Relying on global state |
Keep functions pure — input in, output out |
| Stale data in closures |
Late binding in loops |
Use default arguments or functools.partial |
Start Learning: Local & Global Scope →