Scope
Functions and modules4 min readLesson 2 of 3
Names are looked up in four places, in order: local, enclosing, global, built-in (the LEGB rule).
python
count = 0 # global
def bump():
global count # opt in to changing the global
count += 1Without global, assigning to count inside the function creates a local name instead. That is why the version without it raises UnboundLocalError.
Prefer passing values in and returning results over reaching for globals. A function that only reads a global is fine; one that writes it is hard to test.
nonlocal does the same trick for an enclosing function, and is mostly seen in closures:
python
def counter():
total = 0
def step():
nonlocal total
total += 1
return total
return step