Both modules and packages are used to organize and structure Python code, especially in large projects.
However, they differ in scope and organization level.
| Feature | Module | Package |
|---|---|---|
| Definition | A single Python file that contains code (functions, variables, classes). | A collection (directory) of modules organized together. |
| File Type | A single .py file. | A directory containing an __init__.py file (and possibly multiple modules/sub-packages). |
| Purpose | To logically organize and reuse code. | To structure multiple modules into a hierarchy. |
| Import Syntax | import module_name | import package_name.module_name |
| Example | math.py, os.py, or a custom utils.py file. | A folder like numpy, pandas, or my_app/. |
| Contains | Code 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 - bUsage:
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.pyUsage:
from project.utils.math_utils import add_numbersIn Summary:
- A module is a single file of Python code.
- A package is a collection of modules organized in a folder (with an
__init__.pyfile). - Modules help organize code logically, while packages help organize modules hierarchically.
