Learn

Short lessons with real code you can edit and run on the page.

Modules and Imports in Python

Lesson 26 Python 3.14 Runs in your browser Updated
In short

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 math loads a module, and you reach its contents with a dot, as in math.pi.
  • from math import sqrt brings one name into your file, so the call is sqrt(16).
  • import statistics as stats gives a module a shorter name.
  • A file such as helpers.py is a module, and the script you run can import it with import helpers when both are in the same folder.
  • pip install runs 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.

Python
import math

print(math.sqrt(16))
print(math.pi)
print(math.floor(3.7))
Output
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.

  1. Find the module. The Python Standard Library page lists the modules that come with Python.
  2. Import it at the top. Put import statistics at 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.
  3. Use it with a dot. Call its functions as statistics.mean(scores).
Python
import statistics

scores = [70, 85, 90, 85]
print(statistics.mean(scores))
print(statistics.median(scores))
print(statistics.mode(scores))
Output
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.

Python
from math import sqrt, pi

print(sqrt(25))
print(pi)
Output
5.0
3.141592653589793
Python import forms compared
FormExampleHow you call itBest for
importimport mathmath.sqrt(25)Most code, because the prefix shows where each name comes from
from ... importfrom math import sqrtsqrt(25)A few names you use often
import ... asimport statistics as statsstats.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.

Python
import statistics as stats
from math import sqrt as square_root

print(stats.mean([70, 85, 90, 85]))
print(square_root(9))
Output
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.

Common modules in the Python standard library
ModuleWhat it doesExample
mathMath functions and constantsmath.sqrt(16)
randomRandom numbers and random choicesrandom.randint(1, 6)
statisticsAverages, spread and other statisticsstatistics.mean([1, 2, 3])
datetimeDates and timesdatetime.date.today()
jsonReading and writing JSONjson.dumps({"a": 1})
osFiles, folders and the operating systemos.getcwd()
sysThe running Python interpretersys.version
timeClocks and pausestime.sleep(1)
collectionsExtra container typescollections.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.

helpers.py
def greet(name):
    return f"Hello, {name}!"

def shout(text):
    return text.upper() + "!"
main.py
import helpers

print(helpers.greet("Ada"))
print(helpers.shout("hi"))
Terminal
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.

Python
import math

print(__name__)
print(math.__name__)
Output
__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.

Python
def main():
    print("Running the program")

if __name__ == "__main__":
    main()
Output
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.

Terminal (Windows)
python -m pip install requests
Terminal (macOS and Linux)
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 pip or python3 -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.py is imported instead of the real random module, so functions such as random.randint() seem to be missing. The AttributeError message suggests renaming your file, so do that.
  • SyntaxError: invalid syntax. pip install was typed into the interactive shell or a .py file. 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.

Python
import requestz
Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import requestz
ModuleNotFoundError: No module named 'requestz'
Python
print(math.sqrt(16))
Output
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.

Python
numbers = [2, 4, 9]
print(mean(numbers))
print(median(numbers))
Output
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.

  1. 1What does this program print?

    import math
    print(math.sqrt(9))
  2. 2After from math import sqrt, how do you call the function?

  3. 3What does this program print when you run the file directly?

    print(__name__)
  4. 4Where do you run pip install requests?

  5. 5Which of these file names can another Python file import with an import statement?

Frequently asked questions

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. Every .py file is a module, and Python comes with hundreds of modules in its standard library.
What is the difference between a module and a package in Python?
A module is usually a single .py file, and a package is a folder of modules imported under one name, such as email or json. Once imported, a package works like a module. On PyPI, package also means anything you install with pip, which can contain many modules.
What is the difference between import and from import in Python?
import math gives your program the module, and you call its functions with a prefix, as in math.sqrt(16). from math import sqrt brings in the function itself, so the call is sqrt(16), and both forms load the whole module.
Is from module import * bad practice?
In a program, yes. It brings in every public name at once, so a reader can't tell where a name came from, and an imported name can replace one of yours without warning. PEP 8 advises against it, though it is handy for quick tests in the interactive shell.
What does if __name__ == "__main__" do in Python?
It runs the code under it only when the file is run directly. Python sets __name__ to "__main__" in the file you run and to the module's name in a file that is imported, so importing the file doesn't start the program.
How do I install a package with pip?
Open a terminal and run python -m pip install followed by the package name on Windows, or python3 -m pip install on macOS and Linux. pip downloads the package from PyPI, and you then import it like any other module.
Why do I get ModuleNotFoundError in Python?
Python couldn't find a module with that name. The name may be misspelled, your own module may not be in the folder of the script you ran, or the package may not be installed for the Python that runs your code.