Module 17 · Lesson 03
Building a Data Pipeline
Design a data pipeline as small stages: extract records from messy input, validate them, transform them lazily with generators and load the clean results, while keeping rejected rows and counts.
- About 11 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Extract rows without trusting them
- Validate and keep rejects
- Transform with generator stages
- Watch records flow through stages
Small stages, clean data
A pipeline moves data through small steps: read it, check it, change it, then save it.
Extract
Read raw records from a file or a list, without trusting them yet.
Validate
Check each record. Keep the bad ones in a reject list instead of crashing.
Transform
Generator stages convert, clean and add to one record at a time.
Load
Write the clean results once, at the end, and report the counts.
Pipelines everywhere
Most data you see online went through a pipeline first.
- Weather mapsReadings from many stations are checked, converted and averaged every hour.
- Bank statementsPayments are cleaned, sorted and totalled before you see them.
- Music chartsPlays are counted, de-duplicated and ranked every week.
- Fitness appsRaw step counts become daily totals and weekly graphs.
One stage in one line
This line is a whole pipeline stage: check each record, then fix it. Tap each part to see its job.
Part 1 of 4
stage output:A generator: nothing is processed until the next stage asks for a record.
Build a pipeline stage by stage
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Extract
DictReader turns each CSV line into a dictionary keyed by the header.
Your turn: Add a fourth person to the raw text.
import csv, io
raw = """name,age,city
Ana,34,Paris
Ben,x,Lagos
Cai,29,
"""
rows = list(csv.DictReader(io.StringIO(raw)))
for row in rows:
print(row)
print(len(rows), "rows")Press Run to see what it prints.Watch records flow through stages
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- def parse(lines):
- for line in lines:
- name, score = line.split(",")
- yield name, score
- def valid(pairs):
- for name, score in pairs:
- if score.isdigit():
- yield name, int(score)
- data = ["ana,7", "ben,x", "cai,9"]
- result = dict(valid(parse(data)))
- print(result)
- print(sum(result.values()))
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.When do the stages run?
def stage(items):
for x in items:
print("got", x)
yield x
s = stage([1, 2])
print("ready")0 of 6 answered
Common pipeline misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
csv.DictReader(lines) # rows as dicts; every value is a str
def stage(items): # a generator stage
for item in items:
yield change(item)
rejects.append((number, "reason")) # keep bad rows, do not crash
enumerate(rows, start=2) # line numbers after the header
list(gen) # materialize when you need two passes
json.dump(records, f, ensure_ascii=False)
tmp.replace(final) # write then rename
assert read == loaded + rejected # counts must reconcilePress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A complete CSV to JSON pipeline
Read sign-ups from CSV text, reject rows with a missing email or a bad age, turn the good ones into records with typed fields, write them to a JSON file and print a summary that reconciles.
import csv
import json
from pathlib import Path
RAW = """name,email,age
Ana,ana@example.com,34
Ben,,27
Chloé,chloe@example.com,x
Dev,dev@example.com, 41
"""
def extract(text):
for number, row in enumerate(csv.DictReader(text.splitlines()), start=2):
yield number, row
def validate(rows, rejects):
for number, row in rows:
if not row["email"].strip():
rejects.append((number, "missing email"))
elif not row["age"].strip().isdigit():
rejects.append((number, "bad age"))
else:
yield row
def transform(rows):
for row in rows:
yield {"name": row["name"], "email": row["email"].strip(), "age": int(row["age"])}
def load(records, path):
records = list(records)
tmp = Path(path + ".tmp")
tmp.write_text(json.dumps(records, ensure_ascii=False), encoding="utf-8")
tmp.replace(path)
return len(records)
rejects = []
loaded = load(transform(validate(extract(RAW), rejects)), "signups.json")
read = len(RAW.splitlines()) - 1
print(f"read {read}, loaded {loaded}, rejected {len(rejects)}")
print("rejects:", rejects)
print(Path("signups.json").read_text(encoding="utf-8"))
assert read == loaded + len(rejects)Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Reading a generator twice
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
rows = (int(x) for x in ['3', '4', '5']) print(len(list(rows))) print(sum(rows))
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Retail
A nightly sales import
Each shop uploads its till export at closing time. Overnight, a pipeline totals sales per shop for the morning report and lists any rows a manager needs to correct, without letting one typo hide a whole shop's takings.
Why Python fits
yield fromhands on every numbered row from the reader, so the extract stage is one line. The pricing stage both converts and validates, recording a readable reason for each reject rather than crashing ontwo. The report shows the shop totals the business needs and a short to-fix list for the managers.Pythonimport csv EXPORT = [ "shop,item,amount", "leeds,coffee,3.20", "york,cake,2.80", "leeds,tea,two", "york,coffee,3.20", ",juice,2.50", "leeds,cake,2.80", ] def rows(lines): yield from enumerate(csv.DictReader(lines), start=2) def priced(records, rejects): for number, row in records: try: amount = float(row["amount"]) except ValueError: rejects.append(f"line {number}: amount {row['amount']!r}") continue if not row["shop"]: rejects.append(f"line {number}: no shop") continue yield row["shop"], amount rejects = [] totals = {} for shop, amount in priced(rows(EXPORT), rejects): totals[shop] = totals.get(shop, 0) + amount for shop in sorted(totals): print(f"{shop:<6}{totals[shop]:>6.2f}") print("to fix:", *rejects, sep="\n ")OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Should I use pandas for this?
When should a pipeline stop instead of rejecting a row?
Where should the reject list go in a real system?
Are generators always faster?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 10 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.