Sub topic 2
Namespaces and name binding
This chapter assumes you know basic Python syntax (variables, functions, classes) and have run scripts from a terminal. It explains what an import actually changes in your program.
What a namespace is
A namespace is a mapping from names to objects. Python keeps one for each scope: the built-ins, each module, each function call, and each class body. A module's namespace is stored in a dictionary, which you can read as module.__dict__ or vars(module).
import math
print("pi" in vars(math))
print(vars(math)["sqrt"](25))Because math.pi is only an attribute lookup in that dictionary, the dot in math.pi means "find pi in the namespace of math".
Binding names
Binding means attaching a name to an object in the current namespace. Assignment, def, class, for targets, and import all bind names. None of them copy the object. They only create a reference to it.
An import statement is a binding operation, so the form you pick decides which names appear in your namespace:
| Statement | Name bound in your namespace |
|---|---|
| `import math` | `math` |
| `import os.path as osp` | `osp` |
| `from math import sqrt` | `sqrt` |
After from math import sqrt, the name math does not exist in your namespace. The module is loaded, but you hold only a reference to sqrt.
Bindings are separate from the module
A from import copies the reference at that moment. Rebinding your own name does not change the module, and rebinding the module's name does not change yours.
import math
from math import pi
pi = 3
print(pi)
print(math.pi)This prints 3 and then 3.141592653589793. The local pi now points to a different object, and the module's pi is untouched.
The reverse case causes the common error. If a module later rebinds one of its own variables, code that used from module import name keeps the old object. Code that uses module.name sees the new one. For values that change at runtime, such as settings, access them through the module.
How names are looked up
When Python reads a bare name, it searches scopes in this order, known as LEGB:
- Local: the current function.
- Enclosing: any outer functions.
- Global: the current module's namespace.
- Built-in: names such as
lenandprint.
Each module has its own global scope. A global in a.py is not visible in b.py unless b.py imports it. This isolation is the main reason modules exist: two modules can both define total without conflict.
Exercise
A module settings.py contains level = 1. Another file runs from settings import level, and later code calls settings.level = 2 after import settings. What does level hold in the importing file, and why?
Show answer
It still holds 1. The from import bound the name level to the object 1 at import time. Assigning settings.level = 2 rebinds the name inside the settings namespace only. The importing file's own level still points to the old object. Reading settings.level would give 2.