Sub topic 3
The forms of the import statement
This chapter assumes you can write functions and classes, run scripts from a terminal, and know that a module is a Python file you can load from another file. Here you will learn which name each import form creates in your code, and when to choose each one.
Every import binds a name
An import statement does two things. It loads the module, and it binds one or more names in the current namespace. The forms differ in which names they bind.
import math
from math import sqrt
import os.path as osp
print(math.pi)
print(sqrt(16))
print(osp.basename("/tmp/report.txt"))| Statement | Name bound | How you use it |
|---|---|---|
| `import math` | `math` (the module object) | `math.pi` |
| `from math import sqrt` | `sqrt` (the function) | `sqrt(16)` |
| `import os.path as osp` | `osp` (the `os.path` module) | `osp.basename(...)` |
The first form keeps the module name visible at each use, so readers can see where a name came from. The second form is shorter, but the module name is not bound. After from math import sqrt, writing math.pi raises NameError.
Aliases
The as clause chooses the bound name. It works in both styles:
import collections as col
from collections import OrderedDict as ODUse aliases to shorten long names or avoid a clash, and follow common conventions such as import numpy as np. Do not invent cryptic aliases for one-off use.
Dotted names
import os.path imports the package os and its submodule path, but it binds only the top-level name os. You then write os.path.basename(...). With as, the name is bound to the last module in the chain, so import os.path as osp binds osp directly to os.path.
import xml.dom.minidom
print(xml.dom.minidom.__name__)Importing several names, and the star form
You can import several names in one statement:
from math import sqrt, floor, ceilThe star form from math import * binds every public name from the module. It is legal but discouraged. It hides where names come from, and a later name can silently overwrite an earlier one. Linters flag it. Tutorials and interactive sessions are the usual exceptions.
Common errors
ModuleNotFoundError: No module named 'x'means Python could not find the module. You will see how the search works in a later chapter.ImportError: cannot import name 'y' from 'x'means the module loaded, but it has no attributey. Check spelling, or whetherylives in a submodule.NameErrorafterfrom x import yusually means you usedx.somethingwithout ever bindingx.
Exercise
After running import os.path, which of these names is bound: os, path, or os.path? What changes if you write import os.path as osp instead?
Show answer
Only os is bound, and you reach the submodule as os.path. With as osp, only osp is bound, and it refers to the os.path module. The name os is not bound in that case.