Part 02 / Stage 1
Python for integration work
Goal: Build the everyday tooling of customer work — small command-line tools with clean logs, explicit data shapes, and a repo layout you can hand over. Time: ~2.5 hours · Needs: Python 3.14+, the course venv
What you will learn
- Project layout and virtual environments a customer's team can reproduce
- Command-line tools with argparse: sensible flags,
--dry-run, exit codes - Logging: levels, structured JSON logs, what never to log
- Types and dataclasses to make data shapes explicit
- Files and paths with pathlib; CSV, JSON and encodings
- Git habits for working in a customer's repository
Topics in this part
Practice
Work in the course venv. Check each answer by running it; compare with solutions/ only after trying.
Exercise 1: Flags and exit codes
Build an argparse parser for a tool called acme-report with --month (required, YYYY-MM), --format (choices text or json, default text) and --verbose (a switch). Parse a valid argument list and print the namespace; then show that --format xml raises SystemExit with code 2.
Show the solution to Exercise 1
# Exercise 1: acme-report flags and the argparse exit code
import argparse
def build_parser():
p = argparse.ArgumentParser(prog="acme-report")
p.add_argument("--month", required=True, help="YYYY-MM")
p.add_argument("--format", choices=["text", "json"], default="text")
p.add_argument("--verbose", action="store_true")
return p
print(build_parser().parse_args(["--month", "2025-04", "--verbose"]))
try:
build_parser().parse_args(["--month", "2025-04", "--format", "xml"])
except SystemExit as e:
print("bad arguments exit code:", e.code)
Exercise 2: A JSON logger you can reuse
Wrap the lesson's JsonFormatter in a function get_logger(name) that returns a configured logger (INFO level, stdout). Use it to log one INFO event with fields {"rows": 8, "quarantined": 3} and one ERROR without extra fields.
Show the solution to Exercise 2
# Exercise 2: a reusable JSON logger
import json, logging, sys
class JsonFormatter(logging.Formatter):
def format(self, record):
entry = {"level": record.levelname, "logger": record.name, "msg": record.getMessage()}
entry.update(getattr(record, "fields", {}))
return json.dumps(entry)
def get_logger(name):
log = logging.getLogger(name)
if not log.handlers:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
log.addHandler(handler)
log.setLevel(logging.INFO)
return log
log = get_logger("acme-report")
log.info("export cleaned", extra={"fields": {"rows": 8, "quarantined": 3}})
log.error("could not write report")
Exercise 3: Shapes made explicit
Define a Shipment dataclass with shipment_id: str, weight_kg: float | None, status: str. Create one shipment per row id S-1001 and S-1004 (weight missing -> None), put them in a list, and print the ones with a missing weight.
Show the solution to Exercise 3
# Exercise 3: explicit shipment shapes with a dataclass
from dataclasses import dataclass
@dataclass
class Shipment:
shipment_id: str
weight_kg: float | None
status: str
shipments = [
Shipment("S-1001", 120.0, "Delivered"),
Shipment("S-1004", None, "delivered"), # weight missing in the export
]
missing = [s for s in shipments if s.weight_kg is None]
print("missing weight:", missing)
Exercise 4: Read a real messy file
fdelab.SHIPMENTS_CSV is the raw text of Acme's export. Write it to a temp file with pathlib, read it back with csv.DictReader, and print the number of rows and the set of distinct status values exactly as they appear (you will clean them in Part 6).
Show the solution to Exercise 4
# Exercise 4: write the raw export to disk, read it back properly
import csv
import tempfile
from pathlib import Path
from fdelab import SHIPMENTS_CSV
folder = Path(tempfile.mkdtemp())
export = folder / "shipments.csv"
export.write_text(SHIPMENTS_CSV, encoding="utf-8")
with export.open(encoding="utf-8") as f:
rows = list(csv.DictReader(f))
print("rows:", len(rows))
print("raw status values:", sorted({row["status"] for row in rows}))
Mini-project: acme-sync CLI skeleton
Build the skeleton of the sync tool you will finish in Stage 2: an acme-sync command with --since, --dry-run and --page-size, JSON logging of a simulated run (start, two pages, done), and a README-style usage string printed by --help.
A solution is in solutions/mini_acme_sync_skeleton.py.
Stretch: package it with pyproject.toml so pip install . gives a working acme-sync command on the PATH.
Common mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
No --dry-run on a writing tool |
First run writes into a production system sight unseen | Dry-run flag, and make the first run a dry run |
| Free-text logs | Unsearchable in the customer's log platform | One JSON object per line, fields not prose |
| Logging tokens or personal data | Compliance incident, kept for years | Log ids and counts; redact the rest (Part 12) |
| Unstated file encodings | Crashes on the first accented character | encoding="utf-8" explicitly; try utf-8-sig for Excel exports |
| One giant pull request | Stalls in the customer's review for weeks | Small branches, one change each |
Quick recap
- Every project gets its own venv, pinned requirements, and a README that says how to run it.
- argparse gives your tools flags, help text and exit codes, and a
--dry-runflag builds trust. - JSON logs are searchable; secrets and personal data never belong in them.
- Dataclasses make data shapes explicit; Pydantic will enforce them later.
- Use pathlib and explicit encodings for every file the customer hands you.
- In the customer's repo, keep branches small and commit messages readable — and commit no data and no secrets.
Checklist
- I can lay out a hand-over-ready project from memory.
- I built an argparse tool with
--since,--dry-runand a typed flag. - I can explain why argparse exits with code 2.
- I emitted one JSON log line per event with custom fields.
- I can name three things that must never appear in logs.
Read more: argparse tutorial · logging HOWTO · pathlib docs