Python 3D Academyবাংলা

Pipelines: generators feeding generators

🌍 In real life. A juice factory is an assembly line: one station washes the fruit, the next peels it, the last one squeezes it. Each fruit moves along one at a time; nobody waits for a mountain of washed fruit before peeling starts.

Generators can be joined the same way. Each one takes items from the one before, does one small job, and passes them on:

  • a generator can loop over another generator
  • nothing happens until the last one is asked for an item
  • then each item flows through every station before the next item starts

The idea in one sentence: generators can be chained into a pipeline, each taking items from the one before, doing one small job, and passing them on, one item at a time.

Its words:

  • pipeline: generators joined so the output of one is the input of the next
  • stage: one generator in the pipeline, like "keep the big ones" or "square them"
  • yield from other: hand out everything another iterable gives

One station on its own: a filter that lets through only the numbers above 2, and squares them. A pipeline is several of these joined together:

lines = ["  12 ", "", " 7", "oops", "30  "]

def cleaned(rows):
    for row in rows:
        row = row.strip()
        if row != "":
            yield row

def numbers(rows):
    for row in rows:
        if row.isdigit():
            yield int(row)

pipeline = numbers(cleaned(lines))   # nothing has run yet
print(sum(pipeline))
sum() asks numbers() for an item, which asks cleaned(), which reads one line: each line flows all the way through before the next one.

yield from, step by step: when a generator just wants to hand out everything another iterable gives, yield from other does the loop for you:

  1. yield from [1, 2] is the same as for x in [1, 2]: yield x
  2. it is handy for joining several sources, or flattening lists of lists
  3. the outer generator pauses while the inner one is handing out items
def all_orders(shops):
    for orders in shops:
        yield from orders

morning = ["tea", "toast"]
evening = ["rice", "fish", "tea"]
print(list(all_orders([morning, evening])))

Why pipelines? Each stage is a small, testable function that does one job, and joining them is like snapping pipes together. Because items flow one at a time, a pipeline over a huge file uses as little memory as a pipeline over ten lines, and the first result comes out before the last line is even read.

Mistakes and edge cases.

  • A list in the middle. One stage that returns a list instead of yielding makes the whole pipeline wait and fill memory at that point.
  • Nothing happens. Building the pipeline runs nothing; you must loop over (or list()) the last stage.
  • Reusing a stage. Each stage is an iterator: once the items have flowed through, build the pipeline again.
  • yield instead of yield from. yield [1, 2] hands out the list as one item; yield from [1, 2] hands out 1, then 2.

Quiz

  1. What does this print?

    def double(nums):
        for n in nums:
            yield n * 2
    
    def plus_one(nums):
        for n in nums:
            yield n + 1
    
    print(list(plus_one(double([1, 2, 3]))))
  2. What does this print?

    def both():
        yield from "ab"
        yield from [1, 2]
    
    print(list(both()))
  3. In numbers(cleaned(lines)), when does cleaned read the first line?

    • When something first asks numbers() for an item
    • As soon as the line pipeline = … runs
    • Only after it has read every line
  4. What does this print?

    def evens(nums):
        for n in nums:
            if n % 2 == 0:
                yield n
    
    pipe = evens(range(10))
    print(next(pipe), next(pipe), sum(pipe))
  5. Which line has a mistake? (It should give every item of every list.)

    def flatten(lists):
        for inner in lists:
            yield inner
    
    print(list(flatten([[1, 2], [3]])))

Coding tasks

  1. Write a generator cleaned(rows) that yields each row with spaces stripped from both ends, skipping rows that are empty after stripping.

  2. Write a generator flatten(lists) that yields every item of every inner list, in order. Use yield from.

  3. cleaned is written for you. Write a generator numbers(rows) that yields int(row) for every row made only of digits, and a function total(lines) that returns the sum of numbers(cleaned(lines)).