Modules & Packages
Learn how to organize Python code with modules, import variations, packages, and external libraries.
What are Modules?
- Modules are Python files containing functions, classes, and variables.
- They help organize code into reusable and logical components.
- Use the 'import' keyword to access code from other files.
- Python provides many built-in modules (math, random, datetime, etc.).
# Using built-in modules
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.ceil(4.3)) # 5
import random
print(random.randint(1, 10)) # Random number 1-10
Import Variations
- import module → Import entire module
- from module import item → Import specific items
- import module as alias → Use a shorter name
- from module import * → Import everything (not recommended)
# Different import styles
import math
print(math.sqrt(16))
from math import sqrt, pi
print(sqrt(16))
print(pi)
import math as m
print(m.sqrt(16))
# Import with alias
from math import sqrt as square_root
print(square_root(16))
Creating Your Own Modules
- Any .py file can be a module.
- Define functions, classes, and variables in the file.
- Import it in other files using the filename (without .py).
# File: mymath.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
PI = 3.14159
# File: main.py
import mymath
result = mymath.add(5, 3)
print(result) # 8
print(mymath.PI) # 3.14159
# Or import specific items
from mymath import add, PI
print(add(10, 20)) # 30
Packages
- Packages are directories containing multiple modules.
- Must include an __init__.py file (can be empty).
- Organize related modules together for better structure.
- Use dot notation to access submodules.
# Directory structure:
# mypackage/
# __init__.py
# math_utils.py
# string_utils.py
# File: mypackage/math_utils.py
def add(a, b):
return a + b
# File: mypackage/string_utils.py
def uppercase(text):
return text.upper()
# Using the package
from mypackage import math_utils, string_utils
print(math_utils.add(5, 3))
print(string_utils.uppercase("hello"))
Popular Built-in Modules
- math → Mathematical functions
- random → Random number generation
- datetime → Date and time operations
- os → Operating system interface
- json → JSON encoding/decoding
# math module
import math
print(math.pow(2, 3)) # 8.0
# random module
import random
print(random.choice(['a', 'b', 'c']))
# datetime module
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# os module
import os
print(os.getcwd()) # Current directory
# json module
import json
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data)
print(json_str)
Installing External Packages
- Use pip to install packages from PyPI.
- Popular third-party packages: requests, numpy, pandas, flask.
- Use requirements.txt to list project dependencies.
# Install a package
# pip install requests
# Use the package
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
# Create requirements.txt
# requests==2.28.0
# numpy==1.23.0
# Install from requirements.txt
# pip install -r requirements.txt
Real-life Use Case
- Modules and packages allow for clean project structure.
- External libraries (via pip) extend Python’s power.
- Example: Using requests and json modules to fetch and process API data.
import requests, json
# Fetch GitHub API data
response = requests.get("https://api.github.com/users/octocat")
if response.status_code == 200:
data = response.json()
print(json.dumps(data, indent=2))