Part 08 / Topic 1 of 7
Extract, transform, load as separate steps
A pipeline is a script with a future: it will fail at 3am, be re-run by someone else, and need one step changed without touching the rest. Structure buys you that future — three functions, each testable alone:
# examples/02_a_pipeline_as_small_testable_steps.py
import io, sqlite3
import pandas as pd
from fdelab import SHIPMENTS_CSV
def extract():
return pd.read_csv(io.StringIO(SHIPMENTS_CSV), dtype=str)
def transform(df):
df = df.drop_duplicates().copy()
df["status"] = df["status"].str.strip().str.lower().str.replace(" ", "_")
df["customer"] = df["customer"].str.strip()
return df[["shipment_id", "customer", "status"]]
def load(df, db):
db.executemany("INSERT INTO shipments VALUES (?, ?, ?) ON CONFLICT(shipment_id) DO UPDATE "
"SET customer = excluded.customer, status = excluded.status", df.itertuples(index=False))
return db.execute("SELECT COUNT(*) FROM shipments").fetchone()[0]
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE shipments (shipment_id TEXT PRIMARY KEY, customer TEXT, status TEXT)")
raw = extract(); clean = transform(raw); count = load(clean, db)
print({"extracted": len(raw), "after_transform": len(clean), "rows_in_table": count})
print(db.execute("SELECT status, COUNT(*) FROM shipments GROUP BY status ORDER BY status").fetchall())
# {'extracted': 8, 'after_transform': 7, 'rows_in_table': 7}
# [('delayed', 1), ('delivered', 4), ('in_transit', 2)]
The printed dict is already a run report: 8 extracted, 7 after transform (the duplicate fell out), 7 in the table (the upsert from Part 7 keeps re-runs honest). Each step can be unit-tested with a small frame, retried alone, and read by the person debugging at 3am.
🧪 Quick quiz — answer from memory, then check.
- Why split a pipeline into extract, transform and load functions?
Show the answer
Each step can be tested, retried and debugged on its own. The run report shows counts per step: 8 extracted, 7 after transform, 7 in the table. (verified against the example output above)
Done here? The practice set for Part 8 — 4 exercises with solutions — is on the part page.