Chapter 42 of 54

Modules & Packages in Python

So far, every program you've written has lived in a single file. That works for small exercises, but real projects have thousands of lines. Putting everything in one file would be like writing an entire textbook on one page.

Python solves this with modules and packages. They let you split code into separate files and folders, reuse code across programs, and use the huge collection of ready-made tools that come with Python.

What is a Module?

A module is simply a .py file containing Python code (functions, variables, classes) that other programs can import and use.

Every Python file you've written is already a module. The file name (without .py) becomes the module name. So greetings.py is the module greetings.

Python also ships with a large standard library: hundreds of modules like math, random, os and datetime that you can use without installing anything.


Importing a Module

import module

The most common way is to import the whole module and use its contents with a dot:

import math

print(math.sqrt(16))
print(math.pi)
print(math.factorial(5))
print(math.ceil(4.2), math.floor(4.8))

Output:

4.0
3.141592653589793
120
5 4

The math. prefix tells you (and anyone reading your code) exactly where sqrt comes from.

from module import name

If you only need a few things, you can import them directly and skip the prefix:

from math import sqrt, gcd

print(sqrt(25))
print(gcd(12, 18))

Output:

5.0
6

Giving an Alias with as

Long module names can be shortened with as. You'll see this all the time in data science code, like import numpy as np.

import statistics as stats
from math import factorial as fact

print(stats.mean([2, 4, 6, 9]))
print(stats.median([3, 1, 4, 1, 5]))
print(fact(4))

Output:

5.25
3
24

from module import * (Avoid It)

from math import *

print(sqrt(9))

Output:

3.0

This imports every public name from the module. It works, but it's considered bad practice: you can't tell where a name came from, and an imported name can silently overwrite one of your own variables with the same name.

Style

How You Use It

When to Use

import math

math.sqrt(4)

Default choice; clearest

from math import sqrt

sqrt(4)

You use a few names often

import statistics as stats

stats.mean(...)

Long names, common conventions

from math import *

sqrt(4)

Quick experiments only

Exploring a Module

Use dir() to list what a module contains and help() to read its documentation:

import math

names = [n for n in dir(math) if not n.startswith("_")]
print(names[:6])

Output:

['acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2']

Try help(math.sqrt) in the Python shell to see what a function does.


Creating Your Own Module

Let's create a module of our own. Make a folder with two files side by side:

project/
├── greetings.py
└── main.py

greetings.py

PLATFORM = "CS Learning Portal"


def say_hello(name):
    return f"Hello, {name}! Welcome to {PLATFORM}."


def say_bye(name):
    return f"Goodbye, {name}. Keep practising!"

main.py

import greetings

print(greetings.say_hello("Asha"))
print(greetings.say_bye("Asha"))
print(greetings.PLATFORM)

Run main.py from inside the folder:

python main.py

Output:

Hello, Asha! Welcome to CS Learning Portal.
Goodbye, Asha. Keep practising!
CS Learning Portal

That's all it takes. Any function or variable defined at the top level of greetings.py is available through greetings..


The __name__ == "__main__" Check

Every module has a built-in variable called __name__:

  • When you run a file directly, its __name__ is "__main__".

  • When the file is imported, its __name__ is the module's name.

calc.py

def add(a, b):
    return a + b


print("calc.py __name__ is:", __name__)

if __name__ == "__main__":
    # runs only when calc.py is executed directly
    print("Testing add():", add(2, 3))

Running it directly:

python calc.py

Output:

calc.py __name__ is: __main__
Testing add(): 5

Now importing it from another file, use_calc.py:

import calc

print("Result:", calc.add(10, 20))
python use_calc.py

Output:

calc.py __name__ is: calc
Result: 30

The test code inside the if block did not run when the file was imported. That's why you'll see this pattern at the bottom of almost every Python script: it lets a file work both as a runnable program and as an importable module.

Important: Importing a module runs all of its top-level code once. Keep top-level code to definitions, and put "do something" code inside if __name__ == "__main__":.


How Python Finds a Module

When you write import greetings, Python searches in this order:

  1. Already-loaded modules (a cache called sys.modules).

  2. Built-in modules compiled into Python itself, such as sys.

  3. The folders listed in sys.path, in order:

    • the folder containing the script you ran (or the current folder in the interactive shell),

    • folders in the PYTHONPATH environment variable, if set,

    • the standard library folders,

    • the site-packages folder, where packages installed with pip live.

The first match wins. If nothing is found, you get ModuleNotFoundError: No module named 'greetings'.

Modules Are Loaded Only Once

Because of the sys.modules cache, importing the same module twice doesn't run its code twice:

greeter_once.py

print("Loading greeter_once...")

twice.py

import greeter_once
import greeter_once

print("Done")

Output (running python twice.py):

Loading greeter_once...
Done

You may also notice a __pycache__ folder appearing next to your modules. It contains compiled bytecode (.pyc files) so Python can load the module faster next time. It's safe to delete and is usually ignored in Git.


What is a Package?

As a project grows, even modules need organizing. A package groups related modules into a folder.

A package is a folder of modules. It usually contains an __init__.py file, which runs when the package is first imported.

project/
├── store.py
└── shop/                 ← package
    ├── __init__.py       ← marks shop as a package
    ├── cart.py           ← module shop.cart
    └── discount.py       ← module shop.discount

shop/__init__.py (here it only prints a message, so we can see when it runs; it is often left empty)

print("Initializing the shop package")

shop/cart.py

def add_item(cart, item, price):
    cart[item] = price
    return cart


def total(cart):
    return sum(cart.values())

shop/discount.py

from .cart import total


def apply_discount(cart, percent):
    return total(cart) * (100 - percent) / 100

store.py

from shop import cart
from shop.discount import apply_discount

my_cart = {}
cart.add_item(my_cart, "Notebook", 120)
cart.add_item(my_cart, "Pen", 30)

print("Total:", cart.total(my_cart))
print("After 10% off:", apply_discount(my_cart, 10))
python store.py

Output:

Initializing the shop package
Total: 150
After 10% off: 135.0

Absolute vs Relative Imports

  • Absolute import: the full path from the project root, like from shop.cart import total. Clear and recommended in most code.

  • Relative import: starts with dots and is relative to the current package, like from .cart import total (. = this package, .. = the parent package). Only works inside a package.

If you try to run shop/discount.py directly with python shop/discount.py, the relative import fails with ImportError: attempted relative import with no known parent package, because a directly-run file isn't part of a package. Run it as a module from the project folder instead: python -m shop.discount.

Since Python 3.3, a folder without __init__.py can also be imported (a "namespace package"), but beginners should include __init__.py: it makes the intent clear and gives you a place for package setup code.


Useful Standard Library Modules

Module

Used For

Example

math

Mathematical functions

math.sqrt(2), math.gcd(a, b)

random

Random numbers and choices

random.randint(1, 6), random.choice(items)

statistics

Mean, median, mode

statistics.mean(data)

collections

Extra data structures

Counter, deque, defaultdict

os

Files, folders, environment

os.getcwd(), os.listdir()

sys

Interpreter details

sys.path, sys.argv

datetime

Dates and times

Covered in its own chapter

json

Reading/writing JSON

Covered in its own chapter

For example, Counter from collections does the frequency counting you wrote by hand in the Dictionaries chapter:

from collections import Counter

counts = Counter("banana")

print(counts.most_common(2))

Output:

[('a', 3), ('n', 2)]

And random gives a different result each run:

import random

print(random.randint(1, 6))                 # a dice roll
print(random.choice(["rock", "paper", "scissors"]))

Output (yours will differ):

4
paper

Common Mistakes

1. Naming Your File After a Standard Module

If you save your practice file as random.py and write import random inside it, Python finds your file first (the script's folder comes first in sys.path) and imports it instead of the real module:

import random

print(random.randint(1, 6))

Output (when this file is named random.py):

AttributeError: module 'random' has no attribute 'randint' (consider renaming '...\random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)

Python 3.13 and newer add the helpful "consider renaming" hint; older versions show a less helpful message, usually AttributeError: partially initialized module 'random' has no attribute 'randint' (most likely due to a circular import). The fix is to rename your file (and delete any leftover __pycache__ folder). Avoid names like random.py, string.py, json.py or statistics.py for your own files.

2. Other Pitfalls

  • ModuleNotFoundError for your own module – the file isn't in the same folder as the script you ran, or you ran Python from a different folder than you think.

  • Writing import greetings.py – leave out the .py extension.

  • Circular imports – if a.py imports b.py and b.py imports a.py, one of them may see a half-loaded module. Move the shared code into a third module.

  • Expecting changes to show up after re-importing in the same session – because of the cache, an edited module isn't reloaded. Restart the program (or use importlib.reload()).

Final Takeaway

  • A module is a .py file; a package is a folder of modules, usually with an __init__.py.

  • Use import module by default, from module import name for a few frequently used names, and as for aliases. Avoid import *.

  • Wrap script-only code in if __name__ == "__main__":.

  • Python searches the cache, built-ins, then sys.path, and each module is loaded only once.

The standard library already covers a lot, but the real power of Python comes from third-party packages like requests and numpy. In the next chapter, you'll learn how to install them with pip and keep each project's packages separate using virtual environments.