Modules and Imports in Python
A module is a collection of functions and variables, usually saved in a .py file, that other programs can import. import math lets you call math.sqrt(), and from math import sqrt brings in that one function. pip installs packages that don't come with Python.
Key facts
import mathloads a module, and you reach its contents with a dot, as inmath.pi.from math import sqrtbrings one name into your file, so the call issqrt(16).import statistics as statsgives a module a shorter name.- A file such as
helpers.pyis a module, and the script you run can import it withimport helperswhen both are in the same folder. pip installruns in a terminal, not inside Python, and downloads packages from PyPI.
What is a module in Python?
A module is a collection of functions and variables, usually saved in a .py file, that other programs can import. Python comes with hundreds of modules, together called the standard library, and each one groups related tools, such as the math functions in math.
import math
print(math.sqrt(16))
print(math.pi)
print(math.floor(3.7))4.0 3.141592653589793 3
import math loads the module and gives your program the name math. Everything inside is reached with a dot, so math.sqrt means the sqrt function from the math module, and math.floor() rounds down. The dot keeps names apart, so a variable of your own called pi can't clash with math.pi.
How do I import a module in Python?
Write import and the module's name at the top of the file, then use the module's contents with a dot.
- Find the module. The Python Standard Library page lists the modules that come with Python.
- Import it at the top. Put
import statisticsat the start of the file. PEP 8 puts imports at the top, one module per line, so a reader sees what a program depends on at a glance. - Use it with a dot. Call its functions as
statistics.mean(scores).
import statistics
scores = [70, 85, 90, 85]
print(statistics.mean(scores))
print(statistics.median(scores))
print(statistics.mode(scores))82.5 85.0 85
median() averages the two middle values, 85 and 85, so it prints 85.0, and mode() returns the most common value.
Within one run of a program, Python runs a module's code the first time it's imported and reuses the loaded module after that, so a second import of the same module, even from another file, doesn't run it again.
What is the difference between import and from ... import?
import math gives you the module, and from math import sqrt gives you only the names you list. With the second form you call sqrt() without the math. prefix.
from math import sqrt, pi
print(sqrt(25))
print(pi)5.0 3.141592653589793
| Form | Example | How you call it | Best for |
|---|---|---|---|
| import | import math | math.sqrt(25) | Most code, because the prefix shows where each name comes from |
| from ... import | from math import sqrt | sqrt(25) | A few names you use often |
| import ... as | import statistics as stats | stats.mean(scores) | Long module names, or names with a well-known short form |
| from ... import * | from math import * | sqrt(25) | Quick experiments, not program files |
A from import doesn't make Python load less. The whole module is loaded either way, and the form only changes which names your file can use directly, so choose the one that reads best.
from math import * brings in every public name from math at once. PEP 8 advises against it, because nobody reading the file can tell where a name came from.
Star imports are handy in the interactive shell, the >>> prompt you get by typing python or python3 alone in a terminal, where Python runs each line as you type it.
How do I rename a module with as?
Add as and a new name after the module or function you import. That new name is called an alias, and it's the only name your file gets.
import statistics as stats
from math import sqrt as square_root
print(stats.mean([70, 85, 90, 85]))
print(square_root(9))82.5 3.0
Some aliases are shared conventions, such as import numpy as np and import pandas as pd, and following them makes your code look familiar to other Python programmers. NumPy and pandas don't come with Python, so they have to be installed with pip first.
Which modules come with Python?
The standard library is installed along with Python, so its modules need an import line but no pip install. These nine handle common jobs.
| Module | What it does | Example |
|---|---|---|
math | Math functions and constants | math.sqrt(16) |
random | Random numbers and random choices | random.randint(1, 6) |
statistics | Averages, spread and other statistics | statistics.mean([1, 2, 3]) |
datetime | Dates and times | datetime.date.today() |
json | Reading and writing JSON | json.dumps({"a": 1}) |
os | Files, folders and the operating system | os.getcwd() |
sys | The running Python interpreter | sys.version |
time | Clocks and pauses | time.sleep(1) |
collections | Extra container types | collections.Counter("hello") |
Check the standard library before installing a package for a common job, because the tool is often already there.
How do I make my own module in Python?
Save some functions in a .py file and import it by name from another file in the same folder. The file name becomes the module name, so use only letters, digits and underscores, and don't start it with a digit.
def greet(name):
return f"Hello, {name}!"
def shout(text):
return text.upper() + "!"
import helpers
print(helpers.greet("Ada"))
print(helpers.shout("hi"))
python main.py
The editor on this page runs a single file, so try this on your own computer. Save both files in one folder, open a terminal in that folder, and run main.py, with python3 instead of python on macOS and Linux.
Python prints Hello, Ada! and then HI! on the next line. The import works because the first folder Python searches for modules is the one that holds the script you ran. The installing Python lesson shows how to set Python up and run a file.
The first import also creates a __pycache__ folder that holds a translated copy of helpers.py, so the next run of the program loads it faster. It's safe to delete.
What does if __name__ == "__main__" do?
The check runs the code under it only when the file is run directly, not when another file imports it. Python sets __name__ to "__main__" in the file you run, and to the module's own name in a file that is imported.
import math
print(__name__)
print(math.__name__)__main__ math
Put the code that starts the program in a function, and call that function under the check at the bottom of the file.
def main():
print("Running the program")
if __name__ == "__main__":
main()Running the program
Run this file and main() is called. When another file imports it, __name__ holds the module's name and the check is false, so the importing file can use the functions without the program starting.
How do I install a package with pip?
Run pip install with the package's name in a terminal, not inside Python. A package is code someone has published for others to use, and pip downloads it from PyPI, the Python Package Index.
python -m pip install requests
python3 -m pip install requests
This installs requests, a package for downloading web pages. The -m option runs pip with that same python command, so the package lands in the Python that runs your code, and import requests then works there.
pip may also print a notice that a newer pip is available, which you can ignore. On many Linux distributions and with Homebrew's Python, pip refuses with error: externally-managed-environment instead.
In that case, install into a virtual environment, a separate folder of packages for one project. The venv documentation shows how to create one.
Common mistakes with imports in Python
Import errors usually trace back to one of these five mistakes.
- ModuleNotFoundError: No module named 'requestz'. The name is misspelled, or the package isn't installed for the Python you're running. Check the spelling, then install it with
python -m piporpython3 -m pip. - NameError: name 'math' is not defined. Did you forget to import 'math'? The code uses a module that was never imported. Add the import at the top of the file.
- AttributeError: module 'math' has no attribute 'squareroot'. The module exists but has nothing by that name. Check the documentation for the right name, which here is
sqrt. - A file named after a standard module. A file of yours called
random.pyis imported instead of the realrandommodule, so functions such asrandom.randint()seem to be missing. The AttributeError message suggests renaming your file, so do that. - SyntaxError: invalid syntax.
pip installwas typed into the interactive shell or a.pyfile. Run it in a terminal instead.
Run the two broken programs to see the messages. The first needs a package this editor can't install, so fix the second one by adding the missing import.
import requestzTraceback (most recent call last):
File "main.py", line 1, in <module>
import requestz
ModuleNotFoundError: No module named 'requestz'print(math.sqrt(16))Traceback (most recent call last):
File "main.py", line 1, in <module>
print(math.sqrt(16))
^^^^
NameError: name 'math' is not defined. Did you forget to import 'math'?Exercise
Add one line at the top that imports mean and median from the statistics module, so the program prints 5 and 4 without changing the calls. The starter stops with a NameError, because mean is not defined.
numbers = [2, 4, 9]
print(mean(numbers))
print(median(numbers))
5 4
Show the solution
from statistics import mean, median
numbers = [2, 4, 9]
print(mean(numbers))
print(median(numbers))
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this program print?
import math print(math.sqrt(9))math.sqrt() always returns a float, so the square root of 9 prints as 3.0. The math. prefix is needed because import math gives the program only the name math.
-
2After from math import sqrt, how do you call the function?
A from import brings the name sqrt into your file directly. It does not define the name math, so math.sqrt(9) would raise a NameError.
-
3What does this program print when you run the file directly?
print(__name__)Python sets __name__ to __main__ in the file you run. In a file that another file imports, __name__ holds the module's name instead.
-
4Where do you run pip install requests?
pip is a separate program that runs in a terminal. Typing the command into Python gives a SyntaxError, because it is not Python code.
-
5Which of these file names can another Python file import with an import statement?
A module name has to be a valid Python name, so it can use letters, digits and underscores and cannot start with a digit. A hyphen would be read as a minus sign, and a space ends the name.























