0Pricing
Python Academy · Lesson

nonlocal and Mutable State

Modify enclosing scope.

Reading vs writing enclosing variables

An inner function can freely read an enclosing variable, but if it tries to assign to that name, Python treats it as a new local variable instead. This often surprises beginners.

def outer():
    count = 0
    def inner():
        return count
    return inner()
print(outer())

The assignment trap

Assigning to an enclosing name without declaring intent makes it local, so the outer variable is never updated. Here the change is lost.

def outer():
    count = 0
    def bump():
        count = count + 1
    try:
        bump()
    except UnboundLocalError as e:
        print('Error:', e)
outer()

All lessons in this course

  1. First-Class Functions
  2. Closures and Free Variables
  3. nonlocal and Mutable State
  4. Partial Functions
← Back to Python Academy