An import statement loads a Python module and binds a name to the resulting module object. It lets programs reuse variables, functions, and classes instead of repeating their implementations. section 9.0 section 9.1
Use the form that gives the importing code the clearest namespace:
- Use `import os` to bind the module name and access definitions such as `os.path`. section 9.1
- Use `import mymod as mm` to bind a shorter alias, as commonly done with third-party modules. section 9.1
- Use `from os import sep` or `from os import sep, path` to bind selected definitions directly. section 9.1
- Avoid `from module import *` when explicit names make dependencies easier to see; wildcard behavior can be controlled with `__all__`. section 9.9
Import is a statement, not a function call, and names a module rather than a filename. Python searches directories in `sys.path`, loads the first matching module, and records loaded module objects in `sys.modules`; later imports reuse the loaded module while defining the requested name. section 9.1 section 9.5
Split a sales-tax program across modules
Put `calculate_tax` and supporting data in `freedonia.py`, then place the calling program in `use_freedonia.py`. The second file imports the function and evaluates `calculate_tax(500, 'Harpo', 12)` without duplicating the tax logic. section 9.2
Table 9.1 What you need to know
|
Concept
|
What is it?
|
Example
|
To learn more
|
|---|---|---|---|
import
|
Statement for importing modules
|
import os
|
|
from X import Y
|
Imports module X, but only defines Y as a global variable
|
from os import sep
|
|
importlib.reload
|
Re-imports an already loaded module, typically to update definitions during development
|
importlib.reload(mymod)
|
|
pip
|
Command-line program for installing packages from PyPI
|
pip install packagename
|
|
Decimal
|
Class that accurately handles floating-point numbers
|
from decimal import Decimal
|
Compare import forms, aliases, selected-name imports, wildcard imports, module reloading, and related package tools. section 9.1












