1.2.31 · D3Introduction to Programming (Python)

Worked examples — global and nonlocal keywords

2,058 words9 min readBack to topic

This is the worked-examples companion to global and nonlocal keywords. The parent note taught you the two rules:

  1. Assigning a name anywhere in a function makes it local for the whole function body (decided at compile time).
  2. global reaches the module top level; nonlocal reaches the nearest enclosing function.

Here we do nothing but run every possible case so no scenario surprises you. If a word below is unfamiliar (scope, closure, rebind), the parent note and Scope and LEGB rule define it — we assume only those.


The scenario matrix

Every situation this topic can throw at you is one cell of this table. The examples that follow are each tagged with the cell(s) they cover, and together they fill it completely.

# Case class Do you need a keyword? Which one?
C1 Read-only outer variable No
C2 Rebind a module variable Yes global
C3 Rebind an enclosing-function variable Yes nonlocal
C4 Mutate an object (list/dict) — no = on the name No
C5 Degenerate: rebind before reading, no keyword Crashes UnboundLocalError
C6 Wrong keyword: global where you needed nonlocal Crashes / misses SyntaxError or wrong var
C7 Zero enclosing scopes: nonlocal at module top / one level Crashes SyntaxError
C8 Deep nesting — nonlocal picks nearest enclosing only Yes nonlocal (nearest)
C9 Real-world word problem (shared counter / config) Yes global
C10 Exam twist: global creates a module var that didn't exist Yes global
Figure — global and nonlocal keywords

Example 1 — Read-only outer variable (C1)


Example 2 — The classic crash (C5)


Example 3 — Rebind a module variable (C2)


Example 4 — Mutate, don't rebind (C4)


Example 5 — Closure with nonlocal (C3)


Example 6 — Wrong keyword: global for an enclosing var (C6)


Example 7 — nonlocal with no enclosing scope (C7)


Example 8 — Deep nesting: nonlocal picks the nearest enclosing (C8)

Figure — global and nonlocal keywords

Example 9 — Real-world: shared config toggle (C9)


Example 10 — Exam twist: global creates a new module variable (C10)


Recall Which cell is this? Quick self-test
total = 0
def add(v):
    total += v
add(5)

Answer ::: Cell C5 — total += v rebinds total, making it local; the RHS reads it before assignment → UnboundLocalError. Fix with global total.

Connections

  • global and nonlocal keywords
  • Scope and LEGB rule
  • Functions in Python
  • Closures
  • Mutable vs Immutable objects
  • UnboundLocalError
  • Pure functions and side effects