Python tutorials · Part 8 of 8

Python modules, packages and import

A module is a Python file you can reuse; a package is a folder of modules. The import statement is how you bring their code into yours. Here's how it works, and how to fix the errors you'll hit.

Nobody writes every function from scratch. Python ships with a large standard library, and hundreds of thousands of third-party packages sit on PyPI. The import statement is how you use any of it, and how you split your own code across files.

What is a module?

A module is simply a .py file. Its functions, classes and variables become available to any other code that imports it. The math module, for example, is part of the standard library:

import math

print(math.sqrt(49))
print(math.pi)
7.0
3.141592653589793

import math loads the module once and binds the name math to it. You then reach inside with a dot: math.sqrt, math.pi. Keeping the module name in front makes it obvious where each function came from.

The four ways to import

import statistics                    # 1. the whole module
from statistics import mean          # 2. one name from it
from statistics import median as med # 3. one name, renamed
import datetime as dt                # 4. the module, renamed

data = [3, 1, 4, 1, 5]
print(statistics.mean(data), mean(data), med(data))
print(dt.date(2026, 1, 15).isoformat())
2.8 2.8 3
2026-01-15
  • import module: clearest; you always write module.name.
  • from module import name: shorter when you use one name a lot.
  • as creates an alias. The data-science world relies on standard aliases: import numpy as np, import pandas as pd, import matplotlib.pyplot as plt. Use them; every reader expects them.

Avoid from module import *. It dumps every public name into your file, can silently overwrite your own names, and makes it impossible to tell where something was defined.

Useful standard-library modules

You can get a long way without installing anything:

  • math, statistics, random: numbers and basic stats.
  • datetime: dates and times.
  • pathlib, os: files and folders.
  • json, csv: reading and writing common data formats.
  • collections: Counter, defaultdict, deque.
  • itertools: efficient looping tools.
from collections import Counter

words = "the cat and the hat and the bat".split()
print(Counter(words).most_common(2))
[('the', 3), ('and', 2)]

Writing your own module

Any file you write is already a module. Suppose you have helpers.py:

# helpers.py
def clean(text):
    return text.strip().lower()

GREETING = "hello"

In another file in the same folder, you can import it by its file name without .py:

# main.py
import helpers

print(helpers.clean("  Data Science "))   # data science
print(helpers.GREETING)                   # hello

if name == "main"

When Python runs a file directly, it sets that file's __name__ to "__main__". When the file is imported, __name__ is the module's name instead. That lets one file work as both a script and a reusable module:

# helpers.py
def clean(text):
    return text.strip().lower()

if __name__ == "__main__":
    # runs for `python helpers.py`, not for `import helpers`
    print(clean("  TEST  "))

Without that guard, any test code at the bottom of the file would run every time someone imported it.

Packages

A package is a folder of modules. It lets you organise a bigger project:

myproject/
    main.py
    analysis/
        __init__.py
        cleaning.py
        plots.py

From main.py you can write from analysis import cleaning or from analysis.cleaning import clean. The __init__.py file marks the folder as a regular package and runs when the package is first imported. It can be empty.

Installing third-party packages with pip

Packages that aren't in the standard library are installed from PyPI with pip, in a terminal (not inside Python):

python -m pip install pandas

Then import pandas as pd works in your code. Note that the name you install and the name you import aren't always the same: you install scikit-learn but import sklearn.

For real projects, install packages into a virtual environment so each project has its own versions:

python -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install pandas scikit-learn

In Google Colab and Jupyter, most data-science packages are already installed; for anything missing, run %pip install package-name in a cell.

How Python finds a module

When you write import x, Python searches, in order: the folder of the script you're running, then the folders in the PYTHONPATH environment variable, then the standard library and installed packages. The list lives in sys.path. A module is only executed once per program; later imports reuse the already-loaded copy.

Common import errors

  • ModuleNotFoundError: No module named 'pandas': the package isn't installed in the Python you're running. Run python -m pip install pandas with the same python, or check that the right virtual environment or notebook kernel is active.
  • A file that shadows a real module. If you name your own file random.py or pandas.py, import random finds your file first and things break strangely. Rename the file (and delete any __pycache__ folder next to it).
  • ImportError: cannot import name 'x': the module exists but doesn't contain that name. Check spelling and the library version, or look for a circular import, where two modules import each other.
  • Installing sklearn instead of scikit-learn: install with the PyPI name and import with the module name.

Practice

  1. Import sqrt from math and print the square root of 2, rounded to 3 places.
  2. Use random with a fixed seed to make results repeatable: set random.seed(0) and print random.randint(1, 6) twice.
  3. Count letters in "mississippi" with collections.Counter and print the two most common.

Answers

from math import sqrt
print(round(sqrt(2), 3))

import random
random.seed(0)
print(random.randint(1, 6), random.randint(1, 6))

from collections import Counter
print(Counter("mississippi").most_common(2))
1.414
4 4
[('i', 4), ('s', 4)]

Where this shows up in machine learning

Every ML script starts with imports: import numpy as np, import pandas as pd, from sklearn.model_selection import train_test_split, from sklearn.linear_model import LogisticRegression. scikit-learn is a package of sub-packages, which is why you import from paths like sklearn.ensemble. Most "it works on my machine" problems in ML turn out to be environment issues (missing packages, mismatched versions), so understanding imports and virtual environments saves real time.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.