Closures and nonlocal in Python
Inner functions that remember and mutate outer state.
def make_counter(start=0):
count = start
def bump(step=1):
nonlocal count
count += step
return count
return bump
clicks = make_counter()
clicks()
clicks()
third = clicks()
score = make_counter(100)
bonus = score(50)
How it works
bumpcloses overcountfrommake_counter.nonlocallets it rebind that captured variable.- Each counter keeps its own independent state.
Keywords and builtins used here
bumpdefmake_counternonlocalreturn
The run, in numbers
- Lines
- 17
- Characters to type
- 219
- Tokens
- 57
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 34 seconds.
Step 1 of 5 in Decorators & closures, step 5 of 53 in Pythonic Python.