Modules and Packages
## Learning Objectives
- Create and import modules
- Understand the module search path
- Work with packages
- Use pip for package management
## Modules
### What is a Module?
A Python file (`.py`) is a module:
```python
# my_module.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
```
### Importing Modules
```python
import my_module
print(my_module.greet("Alice")) # Hello, Alice!
print(my_module.PI) # 3.14159
```
### Import Specific Items
```python
from my_module import greet, PI
print(greet("Bob")) # Hello, Bob!
print(PI) # 3.14159
```
### Import with Alias
```python
import my_module as mm
print(mm.greet("Charlie")) # Hello, Charlie!
from my_module import greet as say_hello
print(say_hello("David")) # Hello, David!
```
### Import Everything
```python
from my_module import * # Imports all public names
print(greet("Eve")) # Hello, Eve!
# Avoid this in production - unclear what came from where
```
## The Module Search Path
Python looks for modules in order:
1. Current directory
2. `PYTHONPATH` environment variable
3. Installation-dependent default directories
```python
import sys
print(sys.path) # List of directories Python searches
```
## Standard Library Modules
### os Module
```python
import os
print(os.getcwd()) # Current directory
os.listdir(".") # List files
os.mkdir("new_folder") # Create directory
os.rename("old.txt", "new.txt") # Rename
os.remove("file.txt") # Delete file
os.path.exists("file.txt") # Check exists
os.path.join("dir", "file") # Join paths
```
### sys Module
```python
import sys
print(sys.version) # Python version
print(sys.argv) # Command line arguments
sys.exit(0) # Exit program
print(sys.path) # Module search path
```
### math Module
```python
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.ceil(3.2)) # 4
print(math.floor(3.8)) # 3
print(math.pow(2, 3)) # 8.0
print(math.sin(math.pi/2)) # 1.0
```
### random Module
```python
import random
print(random.random()) # Random float 0-1
print(random.randint(1, 6)) # Random int 1-6
print(random.choice(["a", "b", "c"])) # Random choice
print(random.sample([1,2,3,4,5], 3)) # 3 random items
random.shuffle([1,2,3,4,5]) # Shuffle in place
```
### datetime Module
```python
import datetime
now = datetime.datetime.now()
print(now) # 2026-06-23 10:30:45.123456
print(now.year, now.month, now.day) # 2026 6 23
# Date formatting
print(now.strftime("%Y-%m-%d")) # 2026-06-23
print(now.strftime("%H:%M:%S")) # 10:30:45
# Parse date
date = datetime.datetime.strptime("2026-06-23", "%Y-%m-%d")
```
### json Module
```python
import json
data = {"name": "Alice", "age": 30}
json_str = json.dumps(data) # To JSON string
parsed = json.loads(json_str) # From JSON string
# File operations
with open("data.json", "w") as f:
json.dump(data, f)
with open("data.json", "r") as f:
loaded = json.load(f)
```
## Packages
### What is a Package?
A directory with `__init__.py`:
```text
my_package/
__init__.py
module1.py
module2.py
```
### __init__.py
```python
# my_package/__init__.py
from .module1 import func1
from .module2 import func2
__all__ = ["func1", "func2"] # What 'from package import *' gets
```
### Importing from Packages
```python
from my_package import func1
from my_package.module1 import func1
import my_package
```
### Relative Imports
```python
# In my_package/sub_package/module.py
from .. import other_module # Parent package
from . import sibling_module # Same package
```
## pip - Package Manager
### Basic Commands
```bash
pip install package_name # Install
pip install package==1.2.3 # Specific version
pip install "package>=1.0" # Minimum version
pip install -r requirements.txt # From file
```
### Managing Packages
```bash
pip list # List installed
pip show package_name # Show info
pip uninstall package_name # Uninstall
pip freeze > requirements.txt # Save dependencies
```
### Virtual Environments
```bash
python -m venv myenv # Create
source myenv/bin/activate # Activate (Linux/Mac)
myenv\Scripts\activate # Activate (Windows)
pip install package # Install in env
deactivate # Deactivate
```
## Creating Installable Packages
### setup.py
```python
from setuptools import setup, find_packages
setup(
name="mypackage",
version="1.0.0",
packages=find_packages(),
install_requires=[
"requests>=2.25.0",
],
author="Your Name",
description="A short description",
)
```
### pyproject.toml (Modern)
```toml
[build-system]
requires = ["setuptools>=45", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "mypackage"
version = "1.0.0"
dependencies = ["requests>=2.25.0"]
```
## Common Standard Library Packages
| Package | Purpose |
|---------|---------|
| os | Operating system interface |
| sys | System-specific parameters |
| math | Mathematical functions |
| random | Random number generation |
| datetime | Date and time |
| json | JSON encoding/decoding |
| csv | CSV file handling |
| re | Regular expressions |
| collections | Specialized containers |
| itertools | Iterator tools |
| functools | Higher-order functions |
| pathlib | File path operations |
| urllib | URL handling |
| sqlite3 | SQLite database |
| unittest | Testing framework |
## Summary
- Modules are `.py` files containing Python code
- Import with `import module` or `from module import name`
- Use `as` for aliasing
- Packages are directories with `__init__.py`
- `pip install` installs third-party packages
- Use virtual environments to isolate dependencies
- `sys.path` shows where Python looks for modules
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →