Sub topic 2
Namespaces and name binding
This chapter assumes you can write Python functions and classes and run scripts from a terminal. You do not need to know the import statement in detail yet. The next chapters build on it. The goal here is a precise model of what a name is and where Python stores it. Imports, packages, and most import bugs follow from that model.
Names, objects, and bindings
A variable in Python is not a box that holds a value. A name is a label that refers to an object. A binding is the link between a name and an object. A namespace is a mapping from names to objects. Python keeps many namespaces at the same time, and each name lookup consults them in a fixed order.
Assignment is only one of several operations that create bindings. Each of these binds a name in the current namespace:
x = 5andx += 1def f(): ...bindsfto a function objectclass C: ...bindsCto a class objectfor i in ...:bindsion each iterationwith open(p) as fh:bindsfhexcept ValueError as e:bindse(Python deletes it when the block ends)import mathbindsmathto a module object
The last item is why this chapter comes before the import statement. An import is a binding operation that happens to run other code first.
import math
def area(r):
return math.pi * r * r
class Point:
pass
for i in range(2):
pass
print(sorted(n for n in globals() if not n.startswith("__")))This prints ['Point', 'area', 'i', 'math']. The built-in function globals() returns the module's namespace as a dictionary. Names that start with two underscores are set up by Python itself, so the example filters them out.
A module's namespace is a dictionary
Every module object has its own global namespace. It is a plain dict stored in the module's __dict__ attribute. Attribute access on a module is a dictionary lookup, so math.pi and math.__dict__["pi"] give the same object.
You can build a module by hand to see this.
import types
m = types.ModuleType("demo")
m.x = 10
print(m.__dict__["x"])
exec("y = x * 2", m.__dict__)
print(m.y)The first print shows 10. The exec call runs code with m.__dict__ as its globals, so x is found and y is stored back in the same dictionary. The second print shows 20. When Python imports a file, it does roughly this: it creates an empty module object, then runs the file's code with the module's dictionary as the global namespace. A name that a module-level statement binds becomes an attribute of the module.
dir(obj) lists the names in an object's namespace, and vars(obj) returns its __dict__. Both are useful for inspecting a module you do not know well.
Where Python looks: the LEGB rule
When your code reads a bare name such as total, Python searches these namespaces in order and stops at the first match:
- Local: the current function's own names.
- Enclosing: the names of any outer functions that contain this one.
- Global: the names of the current module.
- Built-in: the
builtinsmodule, which holdslen,print,ValueError, and similar names.
If no namespace has the name, Python raises NameError.
Two details matter in practice:
- Class bodies have their own namespace while they run, but functions defined inside a class do not use it as an enclosing scope. A method must reach a class attribute as
self.attrorClassName.attr. from module import *and attribute access such asmodule.namedo not go through LEGB. Attribute access looks only in that one object's namespace.
Reading versus binding inside a function
The search order applies to reads. Binding follows a different rule: a binding always happens in the current local namespace, unless you declare otherwise. Python decides at compile time which names in a function are local. If a function binds a name anywhere in its body, that name is local everywhere in that function.
total = 10
def add(x):
print(total)
total = total + x
add(5)This raises UnboundLocalError. The assignment on the last line makes total local to add, so the print on the line before it reads a local name that has no value yet. The global total is never consulted.
Two statements change where a binding goes:
global namemakes assignments tonametarget the module's namespace.nonlocal namemakes assignments target the nearest enclosing function's variable.
count = 0
def bump():
global count
count += 1
def make_counter():
n = 0
def step():
nonlocal n
n += 1
return n
return step
bump()
bump()
print(count)
counter = make_counter()
counter()
print(counter())This prints 2 and then 2. bump rebinds the module-level count. Each call to make_counter creates a separate n, which step keeps alive.
You only need global or nonlocal to rebind a name. Calling a method on an object, such as items.append(1), does not bind items, so it needs no declaration.
Rebinding is not mutation
Because names are labels, two names can refer to one object. Mutating the object is visible through both names. Rebinding one name leaves the other pointing where it was.
a = [1, 2]
b = a
b.append(3)
print(a)
b = [9]
print(a)The first print shows [1, 2, 3]. After b = [9], a still shows [1, 2, 3].
This difference explains a common import surprise. A from import copies a binding, not a live connection to the other module's name. Chapter 3 covers the import forms, but the effect is easy to see now.
# settings.py
level = 1
def raise_level():
global level
level += 1# main.py
import settings
from settings import level
settings.raise_level()
print(settings.level)
print(level)The output is 2 and then 1. settings.level looks up the name in the module's dictionary each time, so it sees the new binding. The name level in main.py was bound once, to the integer 1, and never updated.
Shadowing and the built-in namespace
Because lookup stops at the first match, a name in an inner namespace shadows the same name in an outer one. Python does not warn you.
print(len("abc"))
len = 99
print(len)
del len
print(len("abc"))This prints 3, 99, and 3 again. Assigning len at module level creates a global that hides the built-in. Deleting it exposes the built-in again. Shadowing a module is the same problem in a worse form. A local file named random.py can hide the standard library's random module. The pitfalls chapter returns to this.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `UnboundLocalError` | The function assigns to a name it also reads earlier | Pass the value in, or declare `global` or `nonlocal` if rebinding is intended |
| Imported value looks stale | `from m import x` copied the binding | Use `import m` and read `m.x` |
| A built-in stops working | A variable reused the built-in's name | Rename the variable |
| `NameError` for a name defined later in the file | The code ran before the binding statement executed | Reorder, or reference the name only inside functions called later |
Exercise
In the code below, what does each print show, and why? x = "module" def outer(): x = "outer" def inner(): return x return inner def other(): return x print(outer()()) print(other()) x = "changed" print(other())
Show answer
The first print shows "outer". Inside inner, the name x is not local, so Python searches the enclosing scope and finds outer's x before reaching the module's. The second print shows "module", because other has no local or enclosing x and reads the global. The third print shows "changed". Functions look up global names when they run, not when they are defined, so other sees the rebinding that happened after its definition.