Importing Modules
A module is simply a file of Python code that other programs can reuse. The import statement lets you borrow tools from modules, so you can calculate square roots, pick random winners or download web pages without writing that code yourself.
What is a module?
Every .py file is a module. When a file contains useful functions, variables or classes, another program can import it and use them. Modules come from three places:
| Source | Examples | How you get it |
|---|---|---|
| The standard library | math, random, datetime, json | Already installed with Python |
| Third-party packages | requests, pandas, django | Installed with pip |
| Your own files | helpers.py, mpesa_utils.py | Files you write in your project |
Splitting code into modules keeps programs organised. Instead of one enormous file, you group related tools together and import them wherever they are needed.
The import statement
The simplest form is import module_name. You then reach the module's contents with dot notation: module.name.
import math print(math.sqrt(144)) # square root print(math.pi) # a constant stored in the module print(math.ceil(4.2)) # round up print(math.floor(4.8)) # round down
The module name acts like a label on a box. Writing math.sqrt makes it clear where sqrt came from, and it stops names from different modules clashing. This "box of names" is called the module's namespace.
Importing specific names with from
If you only need one or two things, use from module import name. The names are copied into your program, so you use them without the module prefix.
from math import sqrt, pi radius = 3 area = pi * radius ** 2 print(round(area, 2)) print(sqrt(81))
This is shorter to type, but a reader has to scroll up to see where sqrt came from. Both styles are fine; choose the one that keeps your code clearest.
import math adds one name (the module) to your program; from math import ... copies the chosen names in directly, so you drop the prefix.Giving a module a nickname with as
The as keyword gives a module (or a name) a shorter alias. Some aliases are so common that every Python developer recognises them, such as import numpy as np and import pandas as pd.
import statistics as stats from datetime import date as Date marks = [62, 75, 88, 91, 70] print(stats.median(marks)) print(stats.mode(["M-Pesa", "Cash", "M-Pesa", "Card"])) print(Date(2026, 3, 14))
Avoid from module import *. It dumps every public name from the module into your program, so you can't tell where a name came from, and it can silently replace names you already have. For example, the os module has its own open() function, and from os import * hides the built-in open() you normally use for files.
Exploring what a module contains
Use dir() to list the names inside a module and help() to read its built-in documentation. Both work in the interactive shell, which makes them handy for exploring.
import math
log_functions = [name for name in dir(math) if name.startswith("log")]
print(log_functions)
The random module is a favourite for games and simulations. Because it produces random values, your results will differ from the example below.
import random print(random.randint(1, 6)) # roll a die print(random.choice(["Nairobi", "Kisumu", "Mombasa"])) # pick one item
How Python finds a module
When you write import something, Python looks in this order:
- The folder containing the script you are running.
- Any folders listed in the
PYTHONPATHenvironment variable (if set). - The standard library.
- The
site-packagesfolder, wherepipinstalls third-party packages.
The full list is stored in sys.path. Python loads each module only once per program run and caches it, so importing the same module in ten places doesn't run its code ten times.
If Python can't find the module anywhere, you get a ModuleNotFoundError. This usually means you misspelt the name or haven't installed the package yet.
import requests
The fix is to install it inside your project's virtual environment, which is covered in pip & virtual environments.
Never name your own file after a module you want to import. If you save a script as random.py and then write import random, Python finds your file first (it's in the script's folder) and you get confusing errors such as "module 'random' has no attribute 'randint'". Rename your file to something like dice_game.py and delete any __pycache__ folder next to it.
Import style tips
- Put all imports at the top of the file, one module per line.
- Group them: standard library first, then third-party packages, then your own modules, with a blank line between groups.
- Prefer
import moduleorfrom module import nameover star imports.
import json import math import requests from budget import add_expense
Key points
- A module is a
.pyfile of reusable code; import it to use its tools. import mathkeeps the prefix (math.sqrt);from math import sqrtdrops it.ascreates an alias, such asimport pandas as pd.ModuleNotFoundErrormeans a typo or a package that isn't installed.- Don't name your files after modules you import. Next, take a tour of the standard library.
Tip: use the ← and → keys to move between pages.
