← Back to Python, page 2

python-0026 · Easy fresher

How does Python's scope rule (LEGB) work, and when do you need global or nonlocal?

Names are looked up in Local, Enclosing function, Global (module) and Built-in scopes, in that order. Assigning to a name inside a function makes it local for the whole function, so reading it before assignment raises UnboundLocalError. global and nonlocal declare that assignment should target the module or enclosing function scope instead.

Full answer
python
x = "global"
def outer():
    x = "enclosing"
    def inner():
        return x
    return inner()
print(outer())

counter = 0
def bump_bad():
    try:
        counter += 1
    except UnboundLocalError as e:
        print("UnboundLocalError:", e)
bump_bad()

def make_counter():
    n = 0
    def step():
        nonlocal n
        n += 1
        return n
    return step
c = make_counter()
print(c(), c(), c())

Output:

text
enclosing
UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value
1 2 3

inner finds x in the enclosing function before the global one. In bump_bad, counter += 1 is an assignment, so counter is local throughout the function and reading it first fails; the message in Python 3.13 names the variable. nonlocal n lets step rebind the enclosing variable, giving a counter that remembers its state. Prefer returning values or using objects over global, which makes code harder to test.

python
x = "global"
def outer():
    x = "enclosing"
    def inner():
        return x
    return inner()
print(outer())

counter = 0
def bump_bad():
    try:
        counter += 1
    except UnboundLocalError as e:
        print("UnboundLocalError:", e)
bump_bad()

def make_counter():
    n = 0
    def step():
        nonlocal n
        n += 1
        return n
    return step
c = make_counter()
print(c(), c(), c())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Lookup order: local, enclosing, global, built-in
  • Assignment makes a name local
  • UnboundLocalError from reading before assigning
  • nonlocal rebinds enclosing names
  • Avoid global state

Common mistakes

  • Shadowing built-ins like list or id
  • Using global to share state between functions

Follow-ups

  • What does a closure capture?
  • Why does shadowing list cause errors later?

Tips

  • Explain why counter is local