Import Modules and Names Explicitly
Core idea
A module groups reusable Python definitions. import math binds a module name; from math import sqrt binds a selected object. as chooses a local alias. Prefer imports that make the origin of a name clear.
Use a qualified name
Save the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
Output: 9.0. The dot accesses sqrt in the math module; sqrt returns a square root as a float.
Import a selected function under an alias
Save the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
from math import sqrt as rootprint(root(49))Output: 7.0. This statement binds root, not math or sqrt in the importing namespace.
Import a project module
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_prices.py
def subtotal(price, quantity): return price * quantitySave the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
Output: 24. The function is defined in bm_prices.py and reused by run.py.
Common mistake
Do not assume from math import sqrt also binds math. Avoid wildcard imports in application code because they can obscure origins. Only import code you trust: module initialization can execute statements.
Practice
Create a module defining a function for adding a fixed shipping fee to a price. Import the function with an alias and then import the module by name; compare both calls.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Choose explicit imports
Check your understanding of import statements.
What does this print?
from math import sqrt as rootprint(root(25))After `import math as m`, which expression calls the imported square root function?
Which import makes the module origin visible at every call site?
What can happen when a trusted local module is first imported?