Python Modules and Packages
1. ✅ What is a Module?
A module is a file containing Python definitions, functions, classes, and variables. The file must have
a .py extension.
🧠 Why Use Modules?
Code reusability
Better organization
Namespace management
✅ Creating a Module
# my_module.py
def greet(name):
return f"Hello, {name}!"
PI = 3.1416
✅ Importing a Module
import my_module
print(my_module.greet("Alice"))
print(my_module.PI)
Other Import Techniques
from my_module import greet
print(greet("Bob"))
from my_module import *
print(PI)
2. 📦 What is a Package?
A package is a collection of modules organized in directories that include a special __init__.py file (may
be empty).
📁 Package Structure Example:
my_package/
├── __init__.py
├── [Link]
└── [Link]
✅ Accessing Modules from a Package
from my_package import module1
[Link]()
from my_package.module2 import another_function
🔸 In Python 3.3+, __init__.py is optional, but still recommended.
3. 🔁 Built-in Modules
Python includes many built-in modules for various tasks.
📌 Examples
import math
print([Link](16)) # 4.0
import random
print([Link](1, 10)) # e.g., 7
import datetime
print([Link]())
Use dir() to explore a module:
import math
print(dir(math))
4. 📦 Installing External Packages
Use pip (Python’s package installer):
pip install requests
✅ Example:
import requests
response = [Link]('[Link]
print(response.status_code)
5. 📁 Relative vs Absolute Imports
✅ Absolute Import
from my_package import module1
1🔄 Relative Import (within a package)
from . import module1
from ..subpackage import module2
6. 🛠 Useful Tools
🔍 help() Function
import math
help(math)
📁 [Link]
Used to see where Python looks for modules.
import sys
print([Link])
You can add custom paths if needed.
7. ✅ Best Practices
Use clear module and package names (lowercase, no spaces)
Group related functions/classes into the same module
Avoid circular imports
Use __all__ to control from module import *
__all__ = ['function1', 'ClassA']
8. 🧪 Example Exercise
Create a module:
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Create a script to use it:
# [Link]
import math_utils
print(math_utils.add(5, 3)) # Output: 8
print(math_utils.subtract(10, 4)) # Output: 6