Scope & Closures
Where does Python look for a name? (LEGB)
- Local: inside the current function
- Enclosing: inside outer functions
- Global: at the top level of the file
- Built-in: names like
print,len
Variables created inside a function are local: they disappear when it returns and don't affect outer variables with the same name.
global and nonlocal
global xlets a function reassign a global variable. Use it rarely; returning values is cleaner.nonlocal xlets an inner function reassign a variable of the enclosing function.
Closures
An inner function that remembers variables from the function that created it, even after that function has finished. They're useful for counters, factories and configuration.
⚠️ Reading an outer variable is always fine. Assigning to it inside a function makes it local, which is why you sometimes see UnboundLocalError.
▶️ Runs in the app.
Example
x = "global"
def show():
x = "local" # a new local variable, the global is untouched
print(x)
show() # local
print(x) # global
def make_counter():
count = 0
def counter():
nonlocal count # reassign the enclosing variable
count += 1
return count
return counter
c = make_counter()
print(c(), c(), c()) # 1 2 3
def multiplier(n):
return lambda value: value * n
double = multiplier(2)
triple = multiplier(3)
print(double(5), triple(5)) # 10 15