Maya needs tomorrow's date on the milk labels and a square root for a tip-splitting idea. The standard library already has both, and she has been writing them by hand. What does an import actually bring into the file?
A module is a file of Python code that you can reuse. The standard library ships with Python and covers math, statistics, random numbers, dates, and much more. An import makes those names available to your program. You will also see import caching, explicit namespaces, and the main guard.
Import a module
import math loads the module and keeps its names inside the math namespace. Call math.sqrt rather than sqrt so a reader can see where the function came from. This also avoids collisions with your own names.
import math
print(math.sqrt(81))
print(math.pi)Names stay inside the module
Import only what you need
from statistics import mean brings one name into the current namespace. It reads well when the name is unambiguous. Avoid from module import * in real code: it hides where names come from and can overwrite existing variables.
from statistics import mean, median
scores = [7, 9, 10]
print(mean(scores))
print(median(scores))A focused import
Aliases and the random module
An alias is useful for a long module name or a conventional short name. import random as rnd still loads the whole module; you simply reach it through rnd. Seed the generator when you need a repeatable example.
import random as rnd
rnd.seed(7)
print(rnd.choice(["latte", "tea", "mocha"]))A short alias
An import is cached
Python loads a module once per process and stores it in sys.modules. A second import binds the same module object; it does not re-run the file. That is why module-level state can be shared, and why expensive setup belongs behind a function or a main guard.
import math
import math as m
import sys
print(math is m)
print("math" in sys.modules)
print(math.sqrt(16))Aliases point at the same module object
Explicit namespaces prevent collisions
import statistics keeps mean inside the module namespace, so a local variable named mean cannot overwrite it. from statistics import mean is shorter but puts the name in your namespace. Choose the form that makes the source obvious.
import statistics
mean = 10
print(mean)
print(statistics.mean([1, 2, 3]))A local name does not overwrite the module
The main guard separates import from execution
When a file is run directly, __name__ is __main__; when it is imported, __name__ is the module name. Put the demonstration or command-line entry point behind if __name__ == "__main__": so importing only defines names.
def main():
print("program starting")
if __name__ == "__main__":
main()
print("module name:", __name__)Import should not start the program
Key points
- import module keeps names inside that module's namespace.
- from module import name brings one name into the current file.
- An alias changes the name you use, not the module itself.
- Prefer explicit imports over wildcard imports.
- Imports are cached; the main guard keeps module-level side effects out of importers.
Common mistakes
- Calling sqrt without importing it or prefixing it with math.
- Using from math import * and losing track of where names came from.
- Assuming random always produces the same value without seeding it.
- Running a report at import time and surprising every caller.
Import math and statistics, then print the square root of 16 and the mean of [2, 4, 6].
Try it yourself
Change the values, predict the output, then run the code. The Python runtime is downloaded the first time you press Run, so the first run can take a few seconds.
Practice this lesson
12 questions with immediate explanations.