Both modules and packages are used to organize and structure Python code, especially in large projects.
However, they differ in scope and organization level.


FeatureModulePackage
DefinitionA single Python file that contains code (functions, variables, classes).A collection (directory) of modules organized together.
File TypeA single .py file.A directory containing an __init__.py file (and possibly multiple modules/sub-packages).
PurposeTo logically organize and reuse code.To structure multiple modules into a hierarchy.
Import Syntaximport module_nameimport package_name.module_name
Examplemath.py, os.py, or a custom utils.py file.A folder like numpy, pandas, or my_app/.
ContainsCode definitions, variables, and functions.Multiple modules and possibly other packages.

🧩 Example 1: Module Example

# File: calculator.py (This is a module)
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Usage:

import calculator

print(calculator.add(5, 3))
print(calculator.subtract(10, 4))

Output:

8
6

🧩 Example 2: Package Example

my_package/
β”‚
β”œβ”€β”€ __init__.py
β”œβ”€β”€ math_operations.py
└── string_operations.py

# math_operations.py
def square(num):
    return num * num

# string_operations.py
def greet(name):
    return f"Hello, {name}!"

Usage:

from my_package import math_operations, string_operations

print(math_operations.square(5))
print(string_operations.greet("Dheeraj"))

Output:

25
Hello, Dheeraj!

🧩 Example 3: Nested Package Structure

project/
β”‚
β”œβ”€β”€ __init__.py
β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ file_utils.py
β”‚   └── math_utils.py

Usage:

from project.utils.math_utils import add_numbers

In Summary:

  • A module is a single file of Python code.
  • A package is a collection of modules organized in a folder (with an __init__.py file).
  • Modules help organize code logically, while packages help organize modules hierarchically.

Scroll to Top