What Are Python Modules and Packages?
Modules and packages allow you to organize your code, reuse functionality, and extend Python’s capabilities with built-in and third-party libraries.
- Modules: Python files (
.py
) containing reusable code such as functions, classes, or variables. - Packages: Collections of modules organized in directories with an
__init__.py
file.
Using Built-in Modules in Python
Python comes with a rich standard library, offering modules for math, file handling, random number generation, and more.
1. math
Module
The math
module provides mathematical functions.
Example:
import math
# Basic math functions
print("Square root:", math.sqrt(16)) # 4.0
print("Power:", math.pow(2, 3)) # 8.0
print("Pi:", math.pi) # 3.141592653589793
Best Practices:
- Import only required functions to save memory.
from math import sqrt, pi
print(sqrt(25), pi)
2. os
Module
The os
module allows you to interact with the operating system.
Example:
import os
# Get the current working directory
print("Current Directory:", os.getcwd())
# Create a new directory
os.mkdir("new_folder")
# List files in a directory
print("Files:", os.listdir())
Best Practices:
- Use
os.path
for cross-platform file path manipulation.
import os
path = os.path.join("folder", "file.txt")
print(path)
3. random
Module
The random
module generates random numbers or selections.
Example:
import random
# Generate a random number
print("Random Number:", random.randint(1, 100))
# Shuffle a list
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print("Shuffled List:", my_list)
# Random choice from a list
print("Random Choice:", random.choice(my_list))
Installing and Using Third-Party Packages in Python
Python’s ecosystem includes thousands of third-party libraries, installable via pip
.
1. Introduction to pip
pip
is Python’s package installer.
Check Installation:
pip --version
2. Installing a Package
Install a package using the pip install
command.
Example:
pip install requests
3. Example with numpy
numpy
is a popular library for numerical computing.
Installation:
pip install numpy
Example:
import numpy as np
# Create an array
arr = np.array([1, 2, 3, 4])
# Perform operations
print("Array:", arr)
print("Mean:", np.mean(arr))
print("Standard Deviation:", np.std(arr))
4. Example with requests
requests
is a library for making HTTP requests.
Installation:
pip install requests
Example
import requests
# Send a GET request
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print("Status Code:", response.status_code)
print("Response JSON:", response.json())
Best Practices for Using Modules and Packages
Use Virtual Environments:
- Isolate your project dependencies using
venv
.
python -m venv myenv
source myenv/bin/activate # On Linux/macOS
myenv\Scripts\activate # On Windows
Document Imports:
- Group and organize imports for readability.
# Standard library imports
import os
# Third-party imports
import numpy as np
# Local imports
from my_module import my_function
Uninstall Unused Packages:
- Remove packages no longer required.
pip uninstall package_name
Keep Dependencies Updated:
- Use
pip list --outdated
to identify outdated packages.
- Use
Use Requirements File:
- Manage dependencies with
requirements.txt
.
- Manage dependencies with
pip freeze > requirements.txt
pip install -r requirements.txt