Python Modules and Packages Explained
In Python, modules and packages are essential concepts for organizing and reusing code.
1. What is a Module?
A module is a single Python file that contains functions, classes, or variables. It helps to break down large programs into smaller, manageable pieces.
Example:
Create a file called math_utils.py:
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
How to Import a Module:
import math_utils
print(math_utils.add(5, 3)) # Output: 8
print(math_utils.subtract(10, 4)) # Output: 6
2. What is a Package?
A package is a folder that contains multiple modules. It makes it easier to group related modules together.
A package must contain a special file called __init__.py (even if it's empty). This file tells Python that the folder is a package.
Example Folder Structure:
my_package/
│
├─ __init__.py # Marks the folder as a package
├─ math_utils.py # Module 1
└─ string_utils.py # Module 2
How to Use a Package:
from my_package import math_utils
from my_package import string_utils
print(math_utils.add(5, 3))
Differences Between Modules and Packages
| Feature | Module | Package |
|---|---|---|
| Structure | Single file | Folder with multiple modules |
| Import | import module |
from package import module |
| Use Case | Small code | Large projects |
| Example | math_utils.py |
my_package/ |
Bonus
You can create Sub-Packages by nesting folders.
Example:
my_project/
├─ ecommerce/
│ ├─ __init__.py
│ ├─ cart.py
│ └─ products.py
└─ __init__.py
Conclusion
| Concept | Purpose | Example |
|---|---|---|
| Module | Code reuse | math_utils.py |
| Package | Code organization | my_package/ |
| Sub-Package | Nested structure | ecommerce/ |
Comments
Post a Comment