Sub topic 3
The forms of the import statement
This chapter assumes you can write Python functions and classes, run scripts from a terminal, and know that a .py file can be loaded as a module. It covers the import forms, what name each one binds in your namespace, and the errors people hit most often.
What an import statement does
An import statement does two things. It finds and loads a module (the next chapters cover how). Then it binds one or more names in the current namespace. The forms differ only in what 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"))Running this prints 3.141592653589793, 4.0, and report.txt. Three different names now exist in the namespace: math, sqrt, and osp. Notice that os and path do not exist as names here.
Form 1: `import module`
import math
print(math.sqrt(2))This binds the name math to the module object. You reach its contents with attribute access, math.sqrt. The module's own names stay inside its namespace, so they cannot collide with yours.
You can import several modules in one statement, as in import os, sys. The style guide (PEP 8) prefers one import per line because it makes diffs and reviews easier.
Form 2: `from module import name`
from math import sqrt, pi
print(sqrt(pi))This binds sqrt and pi directly in your namespace. It does not bind math. This surprises people:
from math import sqrt
try:
math.pi
except NameError as err:
print(err)The output is name 'math' is not defined. The whole math module was loaded, but only sqrt was bound in your namespace.
The bound name is a reference to the same object. It is not a live link to the module's variable. If the module later rebinds that name, your copy keeps the old object:
import types
cfg = types.ModuleType("cfg")
cfg.level = 1
level = cfg.level # what "from cfg import level" does
cfg.level = 2
print(level) # 1
print(cfg.level) # 2For constants this rarely matters. For module-level state that changes, such as a settings value that gets reassigned, import module and module.name always sees the current value.
Form 3: aliases with `as`
An alias binds a different name than the one in the module.
import os.path as osp
from collections import OrderedDict as ODAliases help in three cases:
- A long dotted name is awkward to repeat.
- Two imports would otherwise bind the same name.
- A community convention exists, such as
import numpy as np.
With import a.b.c as x, the name x is bound to the submodule a.b.c itself. Without as, import a.b.c binds only the top-level name a.
import os.path
print(os.path.sep) # binds "os", reaches path as an attribute
import os.path as osp
print(osp.sep) # binds "osp" to the os.path moduleAn alias does not rename the module. The module's __name__ is unchanged, and sys.modules stores it under its real name.
import os.path as osp
print(osp.__name__)On Linux and macOS this prints posixpath, because os.path is an alias to the platform-specific module.
Form 4: `from module import *`
from math import *
print(floor(2.7))This binds every public name from the module. If the module defines __all__, the names in that list are used. Otherwise, every name that does not start with an underscore is used.
Avoid it in real code, for these reasons:
- Readers cannot tell where a name came from.
- Linters cannot detect undefined names.
- A later import can silently overwrite an earlier name.
from os import *
from math import *If both modules exported a name such as open, the second import would win without any warning. The star form is also only allowed at module level. Inside a function it is a SyntaxError.
Star imports are acceptable in an interactive session and in a package's __init__.py when you control both sides. Later chapters cover __all__ in detail.
Summary of what each form binds
| Statement | Names bound in your namespace |
|---|---|
| `import a` | `a` |
| `import a.b.c` | `a` |
| `import a.b.c as x` | `x` (the module `a.b.c`) |
| `from a import b` | `b` |
| `from a.b import c as y` | `y` |
| `from a import *` | each public name in `a` |
`from package import name` can import a submodule
In from a import b, the name b can be an attribute of a, or it can be a submodule of a. Python tries the attribute first. If a has no attribute b, it tries to import a.b as a submodule.
from os import path
from xml import dom
print(path.sep)
print(dom.__name__)This is why from os import path works even though path is a module. It also explains a common source of confusion: when a package's __init__.py defines a name that matches a submodule name, the attribute wins.
Where imports can appear
An import is an ordinary statement. It runs when execution reaches it, so it can appear anywhere a statement can.
def read_json(text):
import json
return json.loads(text)
print(read_json('{"a": 1}'))The name json here is local to the function. The module is loaded on the first call and found in the cache after that, so repeated calls are cheap, though not free. The usual convention is to put imports at the top of the file, after the docstring, in this order, separated by blank lines:
- Standard library modules.
- Third-party packages.
- Your own modules.
Function-level imports have legitimate uses. They delay a slow import until needed, they make an optional dependency truly optional, and they break circular imports. Those cases are covered in later chapters.
Conditional and guarded imports
Because imports are statements, you can wrap them in try and if.
try:
import tomllib
except ModuleNotFoundError:
tomllib = None
print(tomllib is not None)tomllib is in the standard library from Python 3.11. This pattern gives a fallback on older versions. Catch ModuleNotFoundError, not a bare except, so that unrelated errors inside the module are not hidden.
Common errors
Two exceptions cover most failures. Both are subclasses of ImportError, and ModuleNotFoundError is the more specific one.
| Error | Typical message | Usual cause |
|---|---|---|
| `ModuleNotFoundError` | `No module named 'requests'` | Misspelled name, package not installed, or wrong interpreter |
| `ImportError` | `cannot import name 'sqroot' from 'math'` | The module loaded, but it has no such name |
You can see the difference directly:
try:
import no_such_module
except ModuleNotFoundError as err:
print("missing module:", err.name)
try:
from math import sqroot
except ImportError as err:
print("missing name:", err.name)The first branch prints missing module: no_such_module. The second prints missing name: math.
How the forms relate
All three statements trigger the same load. Only the first one to run does the work. The later ones reuse the cached module.
Exercises
Exercise
After running from os import path, which of these names are defined: os, path, or both? Why?
Show answer
Only path. A from-import binds just the names listed. The os module is loaded, but the name os is not bound in your namespace, so using os.getcwd() raises NameError.
Exercise
A module settings.py contains DEBUG = False, and another module runs from settings import DEBUG. Later, settings.DEBUG = True is executed somewhere. What does the other module's DEBUG show, and how would you write the import so it sees the change?
Show answer
It still shows False. The from-import copied a reference to the old object into the other module's namespace. Use import settings and read settings.DEBUG at the point of use, which looks up the current value each time.
Exercise
What name does import xml.etree.ElementTree as ET bind, and what name does import xml.etree.ElementTree bind?
Show answer
With as ET it binds only ET, which refers to the ElementTree submodule. Without as it binds only xml, and you reach the submodule as xml.etree.ElementTree.