typestar

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

  1. bump closes over count from make_counter.
  2. nonlocal lets it rebind that captured variable.
  3. Each counter keeps its own independent state.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 5 in Decorators & closures, step 5 of 53 in Pythonic Python.

← Previous Next →