Scope: global, nonlocal & LEGB

Published by Brayan K

Scope is the set of rules that decides which variable a name refers to, and Python resolves it with the LEGB rule — searching Local, then Enclosing, then Global, then Built-in scopes and using the first match it finds.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Resolve the name where the function was defined

A name is a binding to an object. Calling a function from a different function does not make the caller’s local variables visible to it. For ordinary function code, Python searches the function’s locals, enclosing function scopes, the defining module and then built-ins.

label = "module"
def read_label():
    return label

def caller():
    label = "caller"
    return read_label()

print(caller())
print(label)

# ✅ Expected output:
# module
# module

The local label in caller belongs to caller. read_label was defined at module level, so its unresolved label reaches that module. A closure adds a remembered enclosing function scope; callback factories and late-bound loop variables are taught in Closures & Lexical Scope in Real Projects. This lesson focuses on deciding which binding an assignment changes.

An assignment classifies the name before the function runs

total = 10
def add_one():
    print(total)
    total = 11

add_one()

# ✅ Expected error:
# UnboundLocalError: cannot access local variable 'total' where it is not associated with a value

Python sees the assignment anywhere in the function body and treats total as local throughout that body, unless a declaration says otherwise. At the print line, that local has no value yet. Python does not fall back to the global total. Even an assignment in a branch that is not taken can produce this result. An augmented assignment such as total += 1 also reads and then binds the name.

status = "outside"
def report(change):
    if change:
        status = "inside"
    return status

report(False)

# ✅ Expected error:
# UnboundLocalError: cannot access local variable 'status' where it is not associated with a value

A simple repair is to make the dependency an argument and return the new value. That makes ownership visible at the call site and avoids a hidden module update.

def add_one(total):
    return total + 1

total = 10
total = add_one(total)
print(total)

# ✅ Expected output:
# 11

Rebinding a name and mutating its object are different operations

events = []
def record(message):
    events.append(message)

def replace_events():
    events = ["local replacement"]
    return events

record("opened")
print(replace_events())
print(events)

# ✅ Expected output:
# ['local replacement']
# ['opened']

record reads events and mutates the list it finds. replace_events binds a new local events, leaving the module binding alone. The difference is about assignment to the name, not whether the underlying object changes. A global declaration is needed only if this function intentionally rebinds the module name.

attempts = 0
def count_attempt():
    global attempts
    attempts += 1
    return attempts

print(count_attempt())
print(count_attempt())
print(attempts)

# ✅ Expected output:
# 1
# 2
# 2

global targets the current module, not a universal variable shared automatically by every module. Place the declaration before using the name in that function. For reusable logic, passing state explicitly or storing it on an instance usually makes independent uses easier to test.

Choose an enclosing function binding with nonlocal

count = 100
def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

first = make_counter()
second = make_counter()
print(first(), first(), second())
print(count)

# ✅ Expected output:
# 1 2 1
# 100

nonlocal looks for an existing binding in an enclosing function scope. Each call to make_counter creates a separate count. It does not target the module-level count and cannot invent an enclosing binding. Choose global if the intended owner is the module; choose nonlocal only when an enclosing function already owns the name.

count = 1
def change():
    nonlocal count
    count = 2

# ✅ Expected error:
# SyntaxError: no binding for nonlocal 'count' found

This declaration is rejected while Python compiles the code, before the module's statements run. A module-level count cannot supply the enclosing function binding that nonlocal requires.

Blocks and class bodies do not all behave like function scopes

def last_label():
    for label in ["A", "B"]:
        pass
    if label == "B":
        result = "finished"
    return label, result

print(last_label())
label = "outside"
labels = [label.lower() for label in ["A", "B"]]
print(labels)
print(label)

# ✅ Expected output:
# ('B', 'finished')
# ['a', 'b']
# outside

Ordinary if and for statements keep bindings in their surrounding scope. Comprehension loop variables do not leak into that surrounding scope. A class namespace is another special case: methods use self or the class name to reach class attributes; a bare name in the method does not automatically search that class dictionary.

label = "module"
class Panel:
    label = "class"
    def describe(self):
        return label, self.label

print(Panel().describe())

# ✅ Expected output:
# ('module', 'class')

Finally, a local or global binding can hide a built-in. Naming a list len makes len(...) call that list instead of the usual function. Choose descriptive names such as lengths so the built-in stays available.

len = [1, 2]
print(len("cat"))

# ✅ Expected error:
# TypeError: 'list' object is not callable

Repair a counter without creating a hidden module dependency

The outer function owns the score. Fill the declaration, the name to update and the returned callable. Two counters should remain independent.

def make_score(start):
    score = start
    def add(points):
        ___ score
        score += ___
        return score
    return ___

blue = make_score(10)
gold = make_score(20)
print(blue(3), blue(2), gold(1))

# 👉 replace ___ with nonlocal
# 👉 replace ___ with points
# 👉 replace ___ with add

# ✅ Expected output:
# 13 15 21

Keep a local history and replace it deliberately

Write make_log, returning append and reset functions plus a read function. They share one enclosing list. append should mutate the existing list; reset should rebind the list to a new empty list; read should return a tuple snapshot. Add A and B, retain a snapshot, reset, add C, then print the retained snapshot and current snapshot. Create another log and show it is empty. Use nonlocal only in the function that rebinds the shared name.

def make_log():
    entries = []
    def append(message):
        entries.append(message)
    def reset():
        nonlocal entries
        entries = []
    def read():
        return tuple(entries)
    return append, reset, read

append, reset, read = make_log()
append("A")
append("B")
saved = read()
reset()
append("C")
print(saved)
print(read())
other_append, other_reset, other_read = make_log()
print(other_read())

# ✅ Expected output:
# ('A', 'B')
# ('C',)
# ()

The snapshot holds the earlier values. All three closures consult the same binding for the active log, so reset changes what subsequent operations see. The second factory call creates separate state.

Practice quiz

What does this program print? name = "module" def read(): return name def call(): name = "caller" return read() print(call())

  • caller
  • NameError
  • module
  • None

Answer: module. Lookup follows the definition environment, not the caller’s local names.

What does this program print? items = [] def add(): items.append("A") add() print(items)

  • ['A']
  • []
  • UnboundLocalError
  • None

Answer: ['A']. Mutation reads the existing binding without rebinding items.

Why can a read before an assignment raise UnboundLocalError despite a global with the same name?

  • Global names can never be read in functions
  • The assignment runs first
  • The global is deleted
  • The assignment makes the name local throughout the function

Answer: The assignment makes the name local throughout the function. Classification uses the whole function body; the local is not yet bound.

What does this program print? value = 3 def change(): global value value = 7 change() print(value)

  • 3
  • 7
  • None
  • NameError

Answer: 7. global directs the assignment to the module binding.

Which existing binding can nonlocal target?

  • A built-in function
  • A name in an enclosing function scope
  • Any variable in another module
  • A local in the caller

Answer: A name in an enclosing function scope. nonlocal searches enclosing function scopes and excludes the module scope.

What does this program print? x = "outside" values = [x * 2 for x in [1, 2]] print(x) print(values)

  • 2 [2, 4]
  • outside [1, 2]
  • NameError
  • outside [2, 4]

Answer: outside [2, 4]. The comprehension has its own iteration binding.

What does this program print? name = "global" class C: name = "class" def read(self): return name, self.name print(C().read())

  • ('global', 'class')
  • ('class', 'class')
  • ('global', 'global')
  • NameError

Answer: ('global', 'class'). Bare name and attribute lookup follow different paths.

What does this program print? def outer(): n = 1 def inner(): nonlocal n n += 2 return n return inner f = outer() print(f(), f())

  • 3 3
  • 1 3
  • 3 5
  • 2 4

Answer: 3 5. Both calls update the same enclosing binding.

Continue this course

Related lessons