Lazy Pipelines With itertools

Concepts covered: Recursion

Generators, map and filter all return iterators: objects that compute their next item only when something calls next() on them. Chain them, and each stage pulls from the stage before it. The consumer at the end requests a single item, the request travels back to the source, that item travels forward through every stage, and the source produces nothing more until the next request.

def read(events):
    for e in events:
        print("read", e)
        yield e

def parse(items):
    for e in items:
        print("parse", e)
        yield e.split(":")

events = ["ana:1", "bo:400", "cy:0"]
stage = parse(read(events))
first = next(stage)
print("got", first)
second = next(stage)
print("got", second)
read ana:1
parse ana:1
got ['ana', '1']
read bo:400
parse bo:400
got ['bo', '400']

The trace alternates read, parse, got. A list-based version would read all 3 events, then parse all 3, before handing anything over, holding every event in memory at once. The chain holds the current item per stage, so its memory stays the same whether the source has 3 events or 300 million.

The itertools building blocks

FunctionYieldsStops
`islice(it, n)`The first n itemsAfter n items, leaving the rest unread
`takewhile(pred, it)`Items while pred is trueAt the first false item, which it consumes and drops
`dropwhile(pred, it)`Everything from the first false item onWhen the source ends
`chain(a, b)`All of a, then all of bWhen b ends
`count(start)`start, start + 1, start + 2, ...Never
`accumulate(it)`Running totalsWhen the source ends
`groupby(it, key)`(key, group) for each run of equal keysWhen the source ends
from itertools import count, islice, takewhile, accumulate, chain

minutes = count(0)
likes_per_minute = map(lambda m: (m * 7) % 10, minutes)
running = accumulate(likes_per_minute)
under_cap = takewhile(lambda total: total < 30, running)
print(list(under_cap))

first_three = islice(chain(["ana", "bo"], ["cy", "dee"]), 3)
print(list(first_three))

Output:

[0, 7, 11, 12, 20, 25, 27]
['ana', 'bo', 'cy']

count(0) never runs out, yet the program ends. takewhile stops asking once a running total reaches 30, so map and accumulate each produce 8 values and the source is asked for 8 minutes. The eighth total, 36, was pulled to be tested and then dropped. islice stops after 3 names without touching dee.

An iterator can be read once

An iterator remembers its position and has no rewind. Once a consumer has drained it, the next consumer receives no items and no error. Handing the same iterator to 2 steps is a frequent lazy-pipeline bug.

What does this program print?

likes = map(int, ["3", "12", "7"])
total = sum(likes)
biggest = max(likes, default=0)
print(total, biggest)

When 2 steps need the same items, build a list if the data fits in memory, or call itertools.tee(it, 2) for 2 independent iterators. tee buffers every item one copy has read and the other has not, so it saves memory only while both copies advance close together.

groupby groups consecutive runs

groupby starts a new group every time the key changes between neighbouring items. It never looks back, which is what lets it stay lazy, and it means a key that reappears later in unsorted input becomes a second group.

from itertools import groupby

likes = [("p1", "ana"), ("p1", "bo"), ("p2", "cy"), ("p1", "dee")]

for post, group in groupby(likes, key=lambda like: like[0]):
    print(post, [user for _, user in group])

print("sorted:")
for post, group in groupby(sorted(likes), key=lambda like: like[0]):
    print(post, [user for _, user in group])

Output:

p1 ['ana', 'bo']
p2 ['cy']
p1 ['dee']
sorted:
p1 ['ana', 'bo', 'dee']
p2 ['cy']

Sorting first fixes the grouping but turns the stream into a list. A real stream often arrives ordered by the key already, such as events written per post or per hour, and groupby relies on that order. Each group reads from the shared source, so consume it before asking for the next key: advancing skips whatever the previous group left unread.

About this lesson

This section is part of the Functional Programming: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.