Python Modules and Packages
Modules and Packages in Python help organize code into reusable and manageable units. They play a very important role in building large applications and automation frameworks.
What is a Module in Python?
A module is a Python file that contains variables, functions, and classes.
Any file with a .py extension is considered a module.
Example of a Module
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Importing a Module
Using import
import math_utils
print(math_utils.add(10, 5))
Using from import
from math_utils import add
print(add(10, 5))
Import with Alias
import math_utils as mu
print(mu.subtract(10, 5))
Built-in Modules in Python
Python provides many built-in modules that can be used directly.
- math
- os
- sys
- datetime
- random
Example
import math
print(math.sqrt(16))
What is a Package in Python?
A package is a collection of related modules organized in directories. It helps manage large projects efficiently.
Package Structure
project/
│
├── utils/
│ ├── __init__.py
│ ├── file_utils.py
│ └── string_utils.py
│
└── main.py
Note: The __init__.py file tells Python that the directory
should be treated as a package.
Importing from a Package
from utils.file_utils import read_file
from utils import string_utils
Example of Module inside a Package
# utils/file_utils.py
def read_file(filename):
print("Reading file:", filename)
# main.py
from utils.file_utils import read_file
read_file("data.txt")
__name__ == "__main__"
This condition checks whether the file is run directly or imported as a module.
def show():
print("Hello Python")
if __name__ == "__main__":
show()
Installing External Packages (pip)
Python uses pip to install third-party packages.
pip install requests
Using Installed Package
import requests
response = requests.get("https://example.com")
print(response.status_code)
Modules and Packages in Automation Testing
framework/
│
├── pages/
│ ├── login_page.py
│ └── dashboard_page.py
│
├── tests/
│ └── test_login.py
│
└── utils/
└── config_reader.py
Used in:
- Selenium Page Object Model
- Robot Framework libraries
- API automation frameworks
Difference Between Module and Package
| Module | Package |
|---|---|
| Single Python file | Collection of modules |
| .py file | Directory |
| Easy to create | Used for large projects |
Best Practices
- Keep related code in same package
- Use meaningful module names
- Avoid circular imports
- Use virtual environments
Common Interview Questions
- What is a module?
- What is a package?
- Difference between module and package?
- What is __init__.py?
- What is __name__ == "__main__"?
Conclusion
Modules and packages help organize Python code efficiently. They are essential for building scalable applications and automation testing frameworks.
👉 Learn more Python concepts with real examples on way2testing.com
No comments:
Post a Comment