Python - Standard Library Highlights
Overview
Estimated time: 45–60 minutes
Tour high-impact parts of the standard library you’ll use daily: dates, paths, subprocesses, serialization, and sqlite3.
Learning Objectives
- Use datetime and timezone-safe patterns.
- Manipulate filesystem paths with pathlib.
- Run subprocesses safely and serialize data with json/csv/tomllib.
Prerequisites
datetime
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
print(now.isoformat())
pathlib
from pathlib import Path
p = Path("data") / "file.txt"
print(p.parent, p.name)
subprocess
import subprocess
res = subprocess.run(["echo", "hi"], capture_output=True, text=True, check=True)
print(res.stdout.strip())
Expected Output: hi
tomllib (3.11+)
import tomllib
with open("pyproject.toml", "rb") as f:
data = tomllib.load(f)
print(type(data))
sqlite3
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE t(x int)")
cur.execute("INSERT INTO t VALUES (42)")
cur.execute("SELECT x FROM t")
print(cur.fetchone()[0])
con.close()
Expected Output: 42
Common Pitfalls
- Naive datetimes without timezone info; prefer timezone-aware (UTC).
- Using shell=True with untrusted input in subprocess; pass a list of args.
Checks for Understanding
- What’s the advantage of pathlib over os.path?
- How do you read TOML in Python 3.11+?
Show answers
- Object-oriented, cross-platform path operations and cleaner API.
- Use tomllib:
tomllib.load(f)
Exercises
- Join a directory and filename with pathlib and print the absolute path.
- Run a simple command with subprocess and capture output.