Using Modules
Intermediate · 18 min read · ▶ live playground · ✦ checkpoint
Your file does not have to know how to do everything by itself. When you need square roots, averages, dates, random choices, or JSON later, Python already has whole shelves of tools waiting for you. You reach those tools with imports.
Import a whole module
A module is an importable bundle of reusable Python names, and an import is the statement that brings that bundle, or selected names from it, into your file. The standard library is the collection of modules that ships with Python.
math is a standard-library module. When you import the whole module, Python binds the module object to the name math.
import math
radius = 3
circle_area = math.pi * radius ** 2
print(f"area: {circle_area:.2f}")
print(f"square root: {math.sqrt(81)}")area: 28.27square root: 9.0
The dot in math.sqrt matters. An attribute is a name that belongs to an object; math.sqrt asks the math module object for its sqrt attribute.
This style keeps the source visible. When you read math.sqrt(81), you know sqrt came from math, not from a function defined earlier in your file.
Import selected names
Sometimes a module name repeated everywhere feels noisy. from module import name loads the module, then binds the chosen name directly in your current scope.
from math import ceil, sqrt
from statistics import mean
scores = [82, 91, 77]
average_score = mean(scores)
print(sqrt(81))
print(ceil(average_score))9.084
Now you call sqrt(81), not math.sqrt(81). That is shorter, but it hides the module name at the call site.
Use the shorter form when you import a few clear names that your file uses often. Keep import module when the module name helps the reader, or when many names from the same module appear.
There is one form to recognize and usually avoid as a beginner. A wildcard import is from module import *, which pulls many names from a module into your scope at once. It makes code harder to read because you cannot tell where a name came from without searching.
Rename with as
An alias is another local name for an imported object. The as form lets you choose that name at import time.
import math as number_tools
from statistics import mean as average
scores = [82, 91, 77]
print(number_tools.sqrt(49))
print(average(scores))7.083.33333333333333
as does not change the module. It only changes the name in this file. After import math as number_tools, your code uses number_tools.sqrt(...).
Aliases are useful when a name is long, when a community convention is strong, or when the alias makes the story clearer. They are not a reason to make puzzle names. number_tools is readable. m2 is a future headache.
A name collision happens when two values want the same name in one scope. Aliases can prevent that:
from statistics import mean as average_scorefrom other_module import mean as average_mood
You have not built your own modules yet. That comes in lesson 8.3, where this collision problem becomes more real.
How Python finds a module
When Python sees import math, it does not search the whole computer randomly. The module search path is the ordered list of places Python checks when it needs to find a module.
Think of the search path as a row of shelves. Python checks the first shelf, then the next, and stops when it finds a matching module.
import sys
import math
print("math" in sys.modules)
print(type(sys.path))
print(len(sys.path) > 0)True<class 'list'>True
sys is a standard-library module for information about the Python runtime. sys.path is the search-path list. The exact entries differ between your computer, this browser runtime, and a server, so do not memorize the printed paths.
The usual shape is:
- The folder of the script you are running.
- Any extra folders configured for Python.
- The standard library.
- External packages are code bundles you add from outside Python; lesson 8.4 covers
pip, Python's package installer, and virtual environments, isolated project workspaces for installed packages.
That first bullet explains a real surprise: if you create your own file named random.py, then write import random, Python may find your file before the standard-library random module. The search order decides which module name wins.
On this page, pressing Run starts a fresh playground session, so your imports run again for that Run. Inside one run, Python can reuse modules already recorded in sys.modules.
Explore with dir and help
You do not have to guess what a module contains. dir(value) returns a list of names available on that value. help(value) prints built-in documentation for that value.
import math
interesting = []
for name in dir(math):
if name in ["ceil", "floor", "pi", "sqrt"]:
interesting.append(name)
print(interesting)
help(math.sqrt)['ceil', 'floor', 'pi', 'sqrt']Help on built-in function sqrt in module math:sqrt(x, /) Return the square root of x.
dir(math) shows names such as sqrt, floor, and pi. help(math.sqrt) tells you the call shape and a short description. The / in that help output marks positional-only parameters, the same marker you met in lesson 7.2.
These two tools are perfect when you see an unfamiliar module in real code:
- Import the module.
- Run
dir(module)to scan its names. - Run
help(module.some_name)when one name looks useful. - Try a tiny call before using it in a bigger program.
Try it - borrow the right tools
Run this, then change the scores and radius. After Run, use the REPL under the playground to try help(math.floor) or dir(math).
This is the normal import rhythm. Use module names when they make code clear. Import selected names when that makes the code cleaner. Use aliases when they remove confusion, not when they save two keystrokes.
Checkpoint
Answer all three to mark this lesson complete
Imports turn Python from one file into a toolbox. Next, you will tour the standard library modules worth reaching for first, from numbers and dates to paths, JSON, and specialized collections.