Python Modules and Packages

Reuse code with import, explore the standard library, write your own modules and install packages with pip in a virtual environment.

Lesson 32 of 107Intermediate18 min read

One of the biggest reasons people love Python is that you rarely have to start from scratch. Need random numbers, dates, maths functions or a way to download a web page? Someone has already written well-tested code for it, and you can use it with a single import line.

A module is simply a Python file containing functions, classes and variables. Python ships with a huge standard library of modules, and there are hundreds of thousands more packages on the Python Package Index (PyPI), which you install with a tool called pip. You can also split your own programs into modules to keep them organised.

In this lesson you'll import modules in different ways, meet some of the most useful standard library modules, write and import a module of your own, and install third-party packages safely inside a virtual environment.

Ways to import

Python
import math
print(math.sqrt(16))           # use the module name as a prefix

from random import choice, randint
print(randint(1, 6))           # use the names directly

import datetime as dt
print(dt.date.today())         # a shorter alias
  • import module keeps everything behind the module's name, which makes it clear where each function comes from.
  • from module import name brings in just the names you need.
  • import module as alias gives a long name a short nickname, as in the common import pandas as pd.

Avoid from module import *. It dumps every name into your program, and you can no longer tell where anything came from.

Useful standard library modules

ModuleWhat it gives you
randomrandint, choice, shuffle for games and sampling
mathsqrt, pi, floor, ceil and more
datetimeDates, times and differences between them
os and pathlibFiles, folders and paths
json and csvReading and writing data files
statisticsmean, median, mode
collectionsCounter for counting, and other handy containers

The official documentation at docs.python.org describes every module. When you think "surely someone has solved this", check the standard library first.

Writing your own module

Any .py file can be imported by another file in the same folder. If helpers.py contains:

Python
def format_price(amount):
    return f"£{amount:.2f}"

then another file can use it with from helpers import format_price. Splitting a program into modules keeps each file focused: one for data loading, one for calculations, one for output.

When a file is run directly, Python sets its special variable __name__ to "__main__". When it's imported, __name__ is the module's name. That's why you'll often see:

Python
if __name__ == "__main__":
    main()

Code inside this block runs only when you execute the file itself, not when another file imports it.

Packages and how Python finds modules

When a project grows beyond a few files, group related modules into a package: a folder of modules, usually with an __init__.py file inside it.

Text
shop/
    __init__.py
    pricing.py
    stock.py
main.py

main.py can then write from shop.pricing import add_vat or import shop.stock. The __init__.py file runs when the package is first imported and can be empty. (Python 3.3 and later also allow "namespace packages" without it, but an explicit __init__.py avoids surprises.)

When you write import something, Python searches a list of folders stored in sys.path. The first entry is the folder of the script you ran, followed by the standard library and the site-packages folder where pip installs packages. A module is executed only the first time it is imported; later imports reuse the already-loaded module, so top-level code in a module does not run twice.

pip and virtual environments

pip installs packages from PyPI: pip install requests. To avoid different projects fighting over package versions, create a virtual environment for each project, a private folder of packages:

Terminal
python -m venv .venv
.venv\Scripts\activate          # Windows
source .venv/bin/activate       # macOS and Linux
pip install requests
pip freeze > requirements.txt

Once activated, your terminal prompt shows (.venv) and every pip install goes into that project only. requirements.txt lists the exact packages, so anyone can recreate the environment with pip install -r requirements.txt. Add .venv/ to your .gitignore rather than committing it.

Python Modules Syntax

Imports and environments

import module
from module import name1, name2
import long_module_name as short

if __name__ == "__main__":
    main()
python -m venv .venv
pip install package-name
pip install -r requirements.txt

Python Modules Summary

  • A module is a .py file; import makes its code available.
  • import m, from m import name and import m as alias are the main styles.
  • The standard library includes random, math, datetime, json, csv and much more.
  • if __name__ == "__main__": runs code only when the file is executed directly.
  • Use pip inside a virtual environment, and record packages in requirements.txt.

Python Modules Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A dice game with random

The numbers are random, so your output will differ. This is one possible run.

Python
import random

rolls = [random.randint(1, 6) for _ in range(5)]
print("Rolls:", rolls)
print("Best roll:", max(rolls))

players = ["Ana", "Ben", "Cleo"]
random.shuffle(players)
print("Order:", players)
print("Winner:", random.choice(players))
Output
Rolls: [3, 6, 1, 4, 4]
Best roll: 6
Order: ['Cleo', 'Ana', 'Ben']
Winner: Ana
Line-by-line explanation
  1. Line 3randint(1, 6) includes both 1 and 6. _ is a common name for a loop variable you don't use.
  2. Line 8shuffle() rearranges the list in place.
  3. Line 10choice() picks one random item. Call random.seed(1) first if you need the same results every run, for example when testing.
Example 2

Dates with datetime

Python
from datetime import date, timedelta

start = date(2024, 9, 2)
exam = date(2024, 12, 16)

days_left = (exam - start).days
reminder = exam - timedelta(weeks=1)

print(f"{days_left} days until the exam")
print("Reminder on:", reminder.strftime("%A %d %B"))
Output
105 days until the exam
Reminder on: Monday 09 December
Line-by-line explanation
  1. Line 6Subtracting two dates gives a timedelta; .days is the number of days.
  2. Line 7Subtract one week to set a reminder.
  3. Line 10strftime() formats a date: %A is the weekday, %d the day and %B the month name.
Example 3

Your own module

Two files in the same folder:

Python
# money.py
def format_price(amount, currency="£"):
    return f"{currency}{amount:.2f}"

def add_tax(amount, rate=0.2):
    return round(amount * (1 + rate), 2)

if __name__ == "__main__":
    print("Testing:", format_price(add_tax(10)))
Python
# shop.py
from money import format_price, add_tax

for price in [4.5, 12, 0.99]:
    print(format_price(add_tax(price)))
Output
£5.40
£14.40
£1.19
Line-by-line explanation
  1. Lines 8 to 9This test only runs when money.py itself is executed, not when shop.py imports it. shop.py imports just the two functions it needs, so its output is only the three prices.

Common Python Modules Mistakes

Calling a function without its module name

Don't
import math
print(sqrt(25))      # NameError: name 'sqrt' is not defined
Do
import math
print(math.sqrt(25))

Installing packages globally for every project

Don't
pip install requests flask pandas   # into the system Python
Do
python -m venv .venv
.venv\Scripts\activate
pip install requests flask pandas

A file named after the module you import

Don't
# file saved as random.py
import random
print(random.randint(1, 6))   # AttributeError
Do
# file saved as dice_game.py
import random
print(random.randint(1, 6))

Python Modules in Real Projects

Packages power real Python work

Almost every real project depends on packages: requests for calling web APIs, pandas and matplotlib for data analysis and charts, Django and Flask for websites, and pytest for testing. Each project keeps its own virtual environment and requirements.txt, so a teammate or a server can install exactly the same versions with one command.

Python Modules FAQ

What is the difference between a module, a package and a library?

A module is a single .py file. A package is a folder that groups modules together. "Library" is an informal word for any reusable collection of code, which might be one module or many packages, such as the standard library or pandas.

How do I fix ModuleNotFoundError: No module named ...?

Usually the package is installed in a different Python than the one running your code. Activate the project's virtual environment, then install with python -m pip install name, which guarantees pip belongs to the same interpreter. Also check the spelling, since the install name and import name can differ (pip install beautifulsoup4, then import bs4).

Should I use pip or python -m pip?

python -m pip is the safer habit. It runs pip for exactly the Python you name, which matters when several Python versions are installed. Plain pip works fine once the right virtual environment is active.

What does if __name__ == "__main__" do?

It runs the indented code only when the file is executed directly, for example python report.py. When another file imports report, that block is skipped. This lets one file work both as a reusable module and as a script.

Where can I learn more about pip and virtual environments?

The pip and virtual environments lesson covers creating, activating and rebuilding environments in more detail, and dependency management explains pinning versions for projects you share.

Python Modules Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the line so randint can be used directly.

 random  randint
print(randint(1, 10))
Multiple choiceeasy

Which command installs a package from PyPI?

Predict the outputmedium

What does this print?

import math
print(math.ceil(4.1), math.floor(4.9))
Multiple choicemedium

What does if __name__ == "__main__": do?

Multiple choicehard

Why use a virtual environment for each project?

Python Modules Quiz

5 questions to check what you learned.

  1. What is a Python module?

    • A type of loop
    • A built-in data type
    • A .py file containing code you can import
    • An error message
  2. What does import pandas as pd do?

    • Imports pandas and lets you refer to it as pd
    • Renames the pandas package on disk
    • Installs pandas
    • Imports only the pd function
  3. What file is commonly used to list a project's packages?

    • packages.py
    • requirements.txt
    • pip.json
    • modules.cfg
  4. Why should you avoid from module import *?

    • It's slower to type
    • It doesn't work in Python 3
    • It only imports classes
    • It imports every name, making it unclear where names come from and risking clashes
  5. What is a virtual environment for?

    • Running Python in the browser
    • Making code run faster
    • Keeping each project's installed packages separate
    • Hiding your code