Python Modules & Packages
Introduction to Modules & Packages
Modules are Python files (.py) that group related code. Packages are directories containing an __init__.py to organize modules.
Creating Custom Modules
Create a file indian_utils.py with reusable functions:
# indian_utils.py
def greet(name):
return f"Namaste, {name}!"
# main.py
from indian_utils import greet
print(greet("Rahul")) # Namaste, Rahul!
Using Packages
Packages let you group modules in directories. Example structure:
bharat_tools/ __init__.py maths.py # add functions greetings.py # wish functions
# greetings.py
def wish():
return "Happy Diwali!"
# maths.py
def add(x, y):
return x + y
# usage in main.py
from bharat_tools import maths, greetings
print(maths.add(10, 20)) # 30
print(greetings.wish()) # Happy Diwali!
pip & Virtual Environments
Use venv to isolate dependencies:
# Create and activate venv (Windows) python -m venv env envScriptsactivate # Install packages pip install requests