Skip to contentSkip to navigation

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

Tap any part of the code below, or press Next.1 of 4 explored

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.

Python
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")
Output
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.

  1. def parse(lines):
  2. for line in lines:
  3. name, score = line.split(",")
  4. yield name, score
  5. def valid(pairs):
  6. for name, score in pairs:
  7. if score.isdigit():
  8. yield name, int(score)
  9. data = ["ana,7", "ben,x", "cai,9"]
  10. result = dict(valid(parse(data)))
  11. print(result)
  12. 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 notesOpen

Pipelines as stages

Extract, transform, load

A data pipeline takes records from a source, changes them and writes them somewhere else. The classic name for this is ETL: extract the raw data, transform it into the shape you need, load it into its destination. In practice a fourth step sits between the first two: validate, which decides whether each record is usable at all.

Thinking in stages matters because each stage has a different kind of problem. Extraction deals with files, encodings and formats. Validation deals with rules about the data. Transformation is ordinary Python logic. Loading deals with writing safely. Mixing them in one long loop makes every problem harder to find.

One stage, one job

Give each stage its own function with a clear input and output:

Try it 1: edit me, then Run
def extract(lines):        # raw text in, dictionaries out
    ...

def validate(rows):        # dictionaries in, only good ones out
    ...

def transform(rows):       # good rows in, final records out
    ...

def load(records, path):   # final records in, a file out
    ...
Output
Press Run to see what it prints.

The top of the program then reads like the plan: load(transform(validate(extract(lines))), "out.json"). Each function can be tested on a short list typed into a test, with no files at all.

Extract: read records without trusting them

csv.DictReader turns each line after the header into a dictionary keyed by the column names. It accepts an open file, or any iterable of strings, which makes it easy to test:

Try it 2: edit me, then Run
import csv

lines = ["name,age", "Ana,34", "Ben,x"]
for row in csv.DictReader(lines):
    print(row)
# {'name': 'Ana', 'age': '34'}
# {'name': 'Ben', 'age': 'x'}
Output
Press Run to see what it prints.

Notice that '34' is a string. CSV has no types: every value arrives as text, and a column that is supposed to hold numbers can hold anything. When reading a real file, open it with encoding="utf-8" and newline="" as the CSV lesson showed, so accented names and line endings come through correctly.

Validate: reject, do not crash

A validation function checks one record and reports what is wrong with it. Returning a reason, or None when the record is fine, keeps the rules in one place:

Try it 3: edit me, then Run
def problem(row):
    if not row["name"].strip():
        return "missing name"
    if not row["age"].isdigit():
        return "age is not a number"
    return None
Output
Press Run to see what it prints.

The pipeline then sorts records into two piles. Good ones move on; bad ones go into a list of rejects with the line number and the reason. One malformed row among ten thousand should not throw away the other 9,999, and a reject list tells the person who owns the source exactly what to fix. Some errors should still stop the run: a missing file or a header with the wrong columns means nothing can be trusted, so raising an exception there is right.

Transform with generators

A generator function processes one item and hands it on before it reads the next. Chaining generator stages builds a pipeline in which only one record is in memory at a time:

Try it 4: edit me, then Run
def parsed(rows):
    for row in rows:
        yield row["name"].strip(), int(row["age"])

def adults(people):
    for name, age in people:
        if age >= 18:
            yield name, age
Output
Press Run to see what it prints.

Calling adults(parsed(rows)) does no work yet. Work starts when something asks for a value, such as a for loop or sum. A file of ten million lines flows through the same few objects, so memory use stays flat. Tools from itertools, such as islice to take the first few records while testing, fit straight into the chain.

The price of laziness is that a generator can be read only once. If you need the records twice, for example to count them and then to write them, make a list at that point, or count while you load.

Load: write once, at the end

The load stage should write the destination in one go, after every record has passed through. Writing to a temporary file and then renaming it with Path.replace means a crash halfway through never leaves a half-written output file behind for the next program to read. For JSON, build the list of records and call json.dump once, with ensure_ascii=False if the data has non-English names.

Count everything

A pipeline that runs every night needs to say what it did. Count the rows read, loaded and rejected, and print or log a summary line. The numbers should always reconcile: read equals loaded plus rejected. If they do not, a stage is silently losing records, which is the worst kind of bug in data work because nothing crashes.

Run it twice safely

Pipelines get rerun: after a failure, after a fix, by mistake. A good pipeline is idempotent, meaning running it twice on the same input gives the same output as running it once. Replacing the output file instead of appending to it, and removing duplicate records by a key such as an order number, both help.

Testing the stages

Because each stage takes an iterable and returns one, tests can feed it a list and compare the result: assert list(adults([("Ana", 34), ("Kit", 9)])) == [("Ana", 34)]. Test the awkward cases on purpose: an empty input, a header only, a row with an extra comma, a name with an accent, a number with spaces around it.

Syntax

The general shape of the statements in this lesson.

syntax.py
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 reconcile
Output
Press 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

Intermediate

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.

Python
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)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Each stage is a generator, so the records flow through one at a time until load gathers them for the single write. The reject list travels alongside the stream, and enumerate(..., start=2) gives line numbers that match the file, because line 1 is the header. Writing to a .tmp file and renaming it means signups.json is never half written. The final assert is the reconciliation check: four rows read, two loaded, two rejected.

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.

Buggy code: run it
rows = (int(x) for x in ['3', '4', '5'])
print(len(list(rows)))
print(sum(rows))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints 3 and then 0: the second pass finds the generator already used up

Write this instead

rows = [int(x) for x in ['3', '4', '5']]
print(len(rows))
print(sum(rows))

Why it happens

A generator produces its values once. Counting them with list() consumed every value, so sum() sees nothing.

In the real world

Where this shows up in software people use every day.

  1. A nightly sales import

    Retail

    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 from hands 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 on two. The report shows the shop totals the business needs and a short to-fix list for the managers.

    Python
    import 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  ")
    Output
    Press 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?

For analysis of data that fits in memory, pandas is excellent. Plain Python stages are still worth knowing: they need no extra library, handle input of any size one record at a time, and make every rule explicit and easy to test.

When should a pipeline stop instead of rejecting a row?

When the problem affects everything: the file is missing, the header has the wrong columns, or the encoding is wrong. Rejecting rows makes sense only when each row can be judged on its own.

Where should the reject list go in a real system?

Usually into its own file or table next to the output, with the line number, the reason and the original text, so someone can fix the source and rerun the pipeline.

Are generators always faster?

Not always. Their main benefit is memory: they keep one record at a time. For a few thousand rows a list is just as good and easier to inspect while debugging.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

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.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

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.