Python · Module 4 · Lesson 21 min read

Scope & Closures

Where does Python look for a name? (LEGB)

  1. Local: inside the current function
  2. Enclosing: inside outer functions
  3. Global: at the top level of the file
  4. Built-in: names like print, len

Variables created inside a function are local: they disappear when it returns and don't affect outer variables with the same name.

global and nonlocal

  • global x lets a function reassign a global variable. Use it rarely; returning values is cleaner.
  • nonlocal x lets an inner function reassign a variable of the enclosing function.

Closures

An inner function that remembers variables from the function that created it, even after that function has finished. They're useful for counters, factories and configuration.

⚠️ Reading an outer variable is always fine. Assigning to it inside a function makes it local, which is why you sometimes see UnboundLocalError.

▶️ Runs in the app.

Example

Python
x = "global"

def show():
    x = "local"          # a new local variable, the global is untouched
    print(x)

show()                   # local
print(x)                 # global

def make_counter():
    count = 0
    def counter():
        nonlocal count   # reassign the enclosing variable
        count += 1
        return count
    return counter

c = make_counter()
print(c(), c(), c())     # 1 2 3

def multiplier(n):
    return lambda value: value * n

double = multiplier(2)
triple = multiplier(3)
print(double(5), triple(5))   # 10 15