Modules and packages help you organize your Python code into reusable components. Instead of writing everything in one long file, you can split your code into logical pieces.
What Are Modules?
A module is simply a Python file containing functions, classes, and variables. Any .py file can be imported as a module.
Creating Your First Module
Create a file called math_utils.py:
# math_utils.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
PI = 3.14159
Importing Modules
Use the import statement to use code from other modules:
# Import entire module
import math_utils
result = math_utils.add(5, 3)
print(math_utils.PI)
# Import specific functions
from math_utils import add, PI
result = add(5, 3)
print(PI)
# Import with alias
import math_utils as mu
result = mu.multiply(4, 7)
Built-in Modules
Python comes with many useful built-in modules:
# Math module
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
# Random module
import random
print(random.randint(1, 10)) # Random number 1-10
print(random.choice(['a', 'b', 'c'])) # Random choice
# Datetime module
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
The __name__ Variable
Use this special variable to make modules both importable and executable:
# calculator.py
def add(a, b):
return a + b
if __name__ == "__main__":
# This code only runs when file is executed directly
print("Calculator module")
print(f"5 + 3 = {add(5, 3)}")
Installing External Packages
Use pip to install packages from PyPI (Python Package Index):
# Install requests for HTTP requests
pip install requests
# Use in your code
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
Popular Python Packages (2020)
- requests: HTTP library for web APIs
- numpy: Numerical computing
- pandas: Data analysis and manipulation
- matplotlib: Plotting and visualization
- flask: Web framework
Modules and packages are the foundation of Python’s ecosystem, allowing you to leverage thousands of existing solutions and organize your own code effectively.