Python Scope & Namespaces
Understanding scope and namespaces is the key to
understanding why a variable is visible in one place but not in another. Python resolves every name
lookup using the LEGB rule — searching Local, then Enclosing, then Global, then Built-in
scopes in that order. This chapter covers each scope with the LEGB diagram, the global and nonlocal keywords, namespace
internals, closures, and the most common scope pitfalls developers hit in real code.
What is a Namespace?
A namespace is a container that maps names (identifiers) to objects. Think of it as a dictionary where keys are variable names and values are the objects they refer to. Python uses multiple namespaces to keep names from different contexts from colliding.
# Python's namespaces are just dictionaries
x = 42 # adds 'x' to module namespace
def show_namespaces():
y = 10 # adds 'y' to local namespace
# Inspect namespaces
print("Local :", dir())
print("Global :", list(globals().keys())[:5]) # first 5 keys
show_namespaces()
# locals() and globals() return dict of the namespace
print(globals()["x"]) # 42
# Each function call creates its own local namespace
def counter():
count = 0 # fresh namespace every call
return count
# Python has 3 main namespace types:
# 1. Built-in — exists for the lifetime of the interpreter
# 2. Module — created when a module is imported/executed
# 3. Local — created when a function is called, destroyed on return
The LEGB Rule — Python's Scope Resolution Order
When Python encounters a name, it searches four scopes in order —
stopping at the first match. If the name isn't found in any scope, a NameError is raised. The acronym LEGB describes this search
order.
print, len, range, list, True, etc. Searched last.NameErrorx = "global" # G — global scope
def outer():
x = "enclosing" # E — enclosing scope for inner()
def inner():
x = "local" # L — local scope of inner()
print(x) # "local" — L found first
inner()
outer()
print(x) # "global" — module-level x unchanged
# Remove inner's x — Python climbs to Enclosing
def outer2():
x = "enclosing"
def inner2():
print(x) # "enclosing" — E found (no local x)
inner2()
outer2()
# Built-in — print and len are always available
print(len([1, 2, 3])) # 3 — B found last
Local Scope
Every function call creates a new local scope (a fresh namespace). Variables assigned inside a function exist only within that function — they are created when the function is called and destroyed when it returns. Parameters are also local.
total = 100 # global variable
def calculate(price): # price → local parameter
tax = price * 0.18 # tax → local variable
total = price + tax # local 'total' shadows global 'total'
return total
print(calculate(500)) # 590.0
print(total) # 100 — global total UNCHANGED
# Local variables are NOT accessible outside
# print(tax) → NameError: name 'tax' is not defined
# Each call gets its own fresh local namespace
def counter():
count = 0
count += 1
print(count)
counter() # 1
counter() # 1 — fresh namespace, count reset each call
counter() # 1
# locals() returns the current local namespace as dict
def inspect_local():
a, b = 1, 2
print(locals()) # {'a': 1, 'b': 2}
inspect_local()
Global Scope & the global Keyword
Variables assigned at the module (file) level are in global scope.
Functions can read global variables without any keyword, but to reassign a global variable
from inside a function you must declare it with global. Without it, Python
treats the assignment as creating a new local variable.
count = 0 # global variable
# ✅ Reading a global — no keyword needed
def show_count():
print(f"Count is: {count}") # reads global count
show_count() # Count is: 0
# ❌ Reassigning global without global keyword → creates local
def increment_bad():
count = count + 1 # UnboundLocalError!
# increment_bad() → UnboundLocalError: local variable 'count'
# referenced before assignment
# ✅ Correct — declare global first
def increment():
global count # tells Python: use the global 'count'
count += 1
increment()
increment()
print(count) # 2
# Multiple globals in one statement
def reset():
global count, name
count = 0
name = "Alice"
# ⚠️ Best practice — avoid global when possible
# Better: use function parameters and return values
def better_increment(c):
return c + 1 # pure function, no side effect
count = better_increment(count)
print(count) # 3
global sparingly — typically only for module-level
constants or simple counters in scripts.
Enclosing Scope & Closures
The enclosing scope exists when a function is nested inside another
function. The inner function can read variables from the outer (enclosing) function's scope. A
closure is an inner function that remembers the enclosing scope's variables even
after the outer function has returned. Use nonlocal to rebind an
enclosing variable.
# ── Enclosing scope — read enclosing variable ────────
def outer():
message = "Hello from outer!"
def inner():
print(message) # reads enclosing variable — E in LEGB
inner()
outer() # Hello from outer!
# ── Closure — inner function survives outer ───────────
def make_multiplier(n):
def multiplier(x):
return x * n # 'n' is captured from enclosing scope
return multiplier # return the inner function (a closure)
double = make_multiplier(2) # outer() finished, but 'n=2' is remembered
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
print(double.__closure__[0].cell_contents) # 2
# ── nonlocal — rebind an enclosing variable ───────────
def make_counter():
count = 0 # enclosing variable
def increment():
nonlocal count # ← without this: UnboundLocalError
count += 1
return count
def reset():
nonlocal count
count = 0
return increment, reset
inc, rst = make_counter()
print(inc()) # 1
print(inc()) # 2
print(inc()) # 3
rst()
print(inc()) # 1 — reset worked
x from the
nearest enclosing function scope — allowing the inner function to reassign (not just read) it.
Without nonlocal, an assignment inside the inner function creates a
new local variable instead.
fn.__closure__ — a tuple of cell objects. You can inspect them to
understand what a closure has captured.Built-in Scope
The built-in scope is the outermost scope in Python — it contains all
of Python's built-in names: functions like print, len, range, types like int, str, list, constants like True, False, None, and exceptions. It's always
available — searched last.
# Built-in names are always available
print(len([1, 2, 3])) # 3
print(type("hello")) # <class 'str'>
print(max(1, 5, 3)) # 5
# Inspect built-in namespace
import builtins
print(dir(builtins)[:10]) # first 10 built-in names
# ⚠️ Shadowing built-ins — avoid this!
# Local/global name shadows the built-in
def bad_example():
list = [1, 2, 3] # ← shadows built-in list!
# list("abc") → TypeError: 'list' is not callable
print(list) # prints [1,2,3] — not the type
# Common shadowing mistakes to avoid:
# list = [...] # shadows list()
# dict = {} # shadows dict()
# input = "data" # shadows input()
# id = 123 # shadows id()
# type = "text" # shadows type()
# Access shadowed built-in via builtins module
def safe_example():
import builtins
my_list = [1, 2] # use a different name
print(builtins.list("abc")) # ['a', 'b', 'c'] — still works
Common Scope Pitfalls
Scope bugs are among the most confusing Python errors. Here are the exact scenarios that trip up developers at every level — with explanations and fixes.
# ── Pitfall 1: UnboundLocalError ─────────────────────
x = 10
def bad():
print(x) # ← Python sees the assignment below
x = 20 # and marks x as LOCAL for the ENTIRE function
# bad() → UnboundLocalError: x referenced before assignment
# Fix: use global x, or don't assign x inside the function
# ── Pitfall 2: Mutable global object modification ─────
items = [] # global list
def add_item(item):
items.append(item) # ✅ no global needed! mutating, not reassigning
add_item("apple")
print(items) # ['apple'] — works without global
# ── Pitfall 3: Late binding closure ───────────────────
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2] ← BUG! All capture final i
# Fix: use default parameter to capture current value
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2] ← correct
# ── Pitfall 4: Shadowing built-ins ────────────────────
# list = [] → now you can't call list() anywhere in this scope
# Fix: rename your variable: items = [], names = [], etc.
# ── Pitfall 5: nonlocal needed, not global ────────────
def outer():
x = 0
def inner():
global x # ← Wrong! Creates a new global x, not enclosing x
x += 1
return x
return inner
# Correct: use nonlocal to refer to outer()'s x
def outer_fixed():
x = 0
def inner():
nonlocal x # ← correct! refers to outer_fixed()'s x
x += 1
return x
return inner
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all scope and namespace examples from this chapter directly in your browser with these free Python environments.
- A namespace is a dictionary mapping names to objects. Python maintains multiple namespaces — built-in, module, and local (per function call).
- The LEGB rule is Python's scope resolution order: Local → Enclosing → Global → Built-in.
The first match wins;
NameErrorif not found anywhere. - Local scope: variables defined inside a function. Each call gets a fresh scope; locals disappear when the function returns.
- Global scope: module-level variables. Functions can read them freely but must declare
global xto reassign them. - Enclosing scope: variables from outer (enclosing) functions, visible to nested (inner)
functions. Use
nonlocal xto rebind an enclosing variable from an inner function. - Built-in scope: always-available names (
print,len,range…). Searched last. Never shadow them with your own variable names. - A closure is an inner function that captures and remembers variables from its enclosing scope even after the outer function has returned.
- Key pitfalls:
UnboundLocalError(assigning to a variable then trying to read it before assignment), late-binding closures in loops, and accidentally shadowing built-ins. - Best practice: avoid global state — prefer passing arguments and returning values to keep functions pure and testable.
The LEGB rule is Python's scope resolution order — the sequence of scopes searched when resolving a name:
- Local — the innermost scope: variables defined in the current function.
- Enclosing — the scope(s) of any enclosing (outer) functions. Relevant for closures.
- Global — the module-level (file-level) scope.
- Built-in — Python's built-in namespace:
print,len,range, etc.
Python searches L → E → G → B and stops at the first match. If the name is
not found in any scope, a NameError is raised.
When Python compiles a function, it scans the entire body at compile time. If it finds an
assignment (x = 20), it marks x as a local variable for the whole function — even
lines before the assignment.
So when print(x) executes, Python looks
in local scope, finds x is marked local but hasn't been assigned
yet, and raises UnboundLocalError: local variable 'x' referenced before assignment.
Fix: add global x at the
top of the function, or restructure to not rebind the global variable inside the function.
A closure is a function object that remembers the values of variables from its enclosing scope even after the outer function has finished and its local frame has been destroyed.
Python creates a closure when: (1) an inner function is defined inside an outer function, (2) the inner function references at least one variable from the outer function's scope, and (3) the inner function is returned (or used as a callback).
def make_adder(n):
return lambda x: x + n # closure captures 'n'
add5 = make_adder(5) # outer() done, but n=5 remembered
print(add5(10)) # 15
global x tells Python that x
refers to the module-level (global) variable — allowing you to rebind it from inside
a function.
nonlocal x tells Python that x refers to a variable in the nearest enclosing function
scope (not global) — allowing an inner function to rebind a variable from an outer
function.
- Use
globalwhen you need to modify a module-level variable from within a function. - Use
nonlocalwhen you need to modify a variable from an enclosing (but not global) function.
Yes — for mutable objects like lists, dicts, and sets, you can mutate the
object without using global. The global keyword is only needed when you want to reassign the
variable (point it to a different object).
items = [1, 2]
def add(x):
items.append(x) # ✅ mutates the object — no global needed
def replace(new):
global items
items = new # ← reassigns — needs global
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.