Python Modules

Python modules are files of Python code that you can reuse in other programs with the import statement. Python ships with a large standard library of modules, and you can install thousands more or write your own.

Importing a Module

There are a few ways to import. You can import the whole module, import specific names from it, or give it a shorter alias.

import math
from statistics import mean, median
import datetime as dt

print(math.gcd(48, 18))
print(mean([4, 8, 9]), median([4, 8, 9]))
print(dt.date(2026, 10, 31).strftime("%A"))
6
7 8
Saturday

Working with Dates: datetime

The datetime module handles dates, times and the difference between them (timedelta).

from datetime import date, timedelta

start = date(2026, 1, 5)
due = start + timedelta(days=30)

print(due)
print(due.strftime("%d %B %Y"))
print((date(2026, 12, 25) - start).days)
2026-02-04
04 February 2026
354

Reading and Writing JSON

The json module converts between Python dictionaries and JSON text, the format used by most web APIs.

import json

order = {"id": 101, "items": ["rice", "tea"], "paid": True}

text = json.dumps(order)
print(text)

data = json.loads('{"city": "Lahore", "zip": 54000}')
print(data["city"], data["zip"] + 1)
{"id": 101, "items": ["rice", "tea"], "paid": true}
Lahore 54001

Create Your Own Module

Any .py file is a module. Save the code below as helpers.py, then import it from another file in the same folder.

# helpers.py
def slugify(title):
    return title.lower().replace(" ", "-")

TAX_RATE = 0.1
# main.py
import helpers

print(helpers.slugify("Python Modules Tutorial"))
print(helpers.TAX_RATE)
python-modules-tutorial
0.1

The __name__ == "__main__" Check

When a file is run directly, its __name__ variable is "__main__". When it is imported, __name__ is the module name. Code inside this check only runs when the file is executed directly, not when imported.

def main():
    print("Running as a script")

if __name__ == "__main__":
    main()
Running as a script

Installing Packages with pip

Third-party packages live on PyPI and are installed with pip from the terminal. It is good practice to create a virtual environment for each project first, so packages do not clash.

python -m venv .venv
.venv\Scripts\activate        # Windows
source .venv/bin/activate     # macOS / Linux
pip install requests

Handy Standard Library Modules

  • math, statistics, random: numbers and maths
  • datetime, time: dates and times
  • json, csv: data formats
  • os, pathlib, shutil: files and folders
  • re: regular expressions
  • collections, itertools: extra data structures and loop tools

Frequently asked questions

What is the difference between a module and a package in Python?

A module is a single .py file. A package is a folder of modules, usually with an __init__.py file, that can be imported as a group.

Is from module import * a good idea?

Generally no. It dumps every name into your file, which can silently overwrite your own variables and makes it unclear where names come from.

How do I see what is inside a module?

Call dir(module_name) to list its names, or help(module_name) to read its documentation.