Python Comprehensions, Iterators and Generators · Lesson 80 of 149

Python Lazy Pipelines and Memory

What you will learn

  • How to chain generators into a lazy pipeline
  • How to see laziness and early stopping in action
  • The itertools toolbox
  • How to measure memory with tracemalloc
  • The pitfalls: one pass, late errors, side effects
  • When to turn a pipeline into a list

1. The idea of a pipeline

Imagine a factory line. Each machine does one small job on one item and passes it on; no machine waits for the whole batch. A lazy pipeline works the same way. Each stage is a generator that takes an iterable and produces another (lessons 12.5 and 12.6). Items flow one at a time through every stage, so nothing large is ever stored.

The pipeline below reads lines of a made-up data file, drops blank lines, splits each line, keeps rows whose second field is a number, and converts them. Each stage prints when it reads, so you can watch the flow:

from itertools import islice

def read_lines():
    for line in ["id,score", "1,90", "2,85", "3,x", "4,70", "", "5,60"]:
        print("  read:", line)
        yield line

def strip_blank(lines):
    return (l for l in lines if l.strip())

def split(lines):
    return (l.split(",") for l in lines)

def valid(rows):
    return (r for r in rows if r[1].isdigit())

def to_int(rows):
    return ((int(a), int(b)) for a, b in rows)

pipeline = to_int(valid(split(islice(strip_blank(read_lines()), 1, None))))
print("pipeline built, nothing read yet")
pipeline built, nothing read yet

Building the pipeline did nothing: no line was read yet. Now ask for just two rows:

print(list(islice(pipeline, 2)))
  read: id,score
  read: 1,90
  read: 2,85
[(1, 90), (2, 85)]

Only three lines were read: the header (skipped by islice(..., 1, None)), and the two rows that were wanted. The pipeline stopped as soon as it had enough, and never touched lines 3 to 7. For a file with millions of lines, that is the difference between instant and very slow.

Quick check: why were only three lines read?

Each stage is lazy, and islice asked for only two rows. The source produced only as many lines as were needed to make them.

Process everything and the whole file is read, one line at a time:

total = sum(score for _, score in to_int(valid(split(islice(strip_blank(read_lines()), 1, None)))))
print(total)
  read: id,score
  read: 1,90
  read: 2,85
  read: 3,x
  read: 4,70
  read: 
  read: 5,60
305

The lines 3,x and the blank one were filtered out along the way. The sum is 90 + 85 + 70 + 60 = 305.

2. Why stages are small functions

Each stage does one thing, which makes the pipeline easy to read, test and change. You can test valid on a small list, replace to_int with something else, or insert a new stage. It is the same principle as small functions (lesson 11.8), applied to streams of data.

A stage can be a generator function (with yield) or a generator expression (in brackets). Use whichever is clearer:

Stage kind Best for
generator expression a one-line filter or transform
generator function several steps, or state between items (a running total)

3. The itertools toolbox

The standard library module itertools is a box of ready-made lazy tools for exactly this. All of them take iterables and give iterators:

Tool What it does Example result
islice(it, stop) or islice(it, start, stop, step) takes a slice of any iterator list(islice(range(100), 2, 8, 3)) is [2, 5]
takewhile(f, it) takes items while f is true, then stops [1, 2, 3, 5, 1] gives [1, 2, 3] for x < 4
dropwhile(f, it) skips items while f is true, then takes the rest the same input gives [5, 1]
chain(a, b, ...) one stream from several chain([1, 2], "ab") gives 1, 2, a, b
chain.from_iterable(x) joins an iterable of iterables [[1], [2, 3]] gives 1, 2, 3
accumulate(it) running totals (or another function) [1, 3, 6, 10] for [1, 2, 3, 4]
pairwise(it) neighbouring pairs (Python 3.10 and later) [(1, 4), (4, 9), (9, 16)]
batched(it, n) groups of n (Python 3.12 and later) [(0, 1, 2), (3, 4, 5), (6,)]
starmap(f, pairs) calls f(*pair) for each pair starmap(pow, [(2, 3), (3, 2)]) gives 8, 9
filterfalse(f, it) keeps items where f is false the opposite of filter
compress(data, flags) keeps data items whose flag is true compress("abcd", [1, 0, 1, 0]) gives a, c
groupby(it, key) groups runs of equal keys (data must be sorted) lesson 9.6
count, cycle, repeat endless streams lesson 12.4
product, permutations, combinations all arrangements lesson 12.5 and chapter 17
tee(it, n) n independent copies of one iterator lesson 12.4
from itertools import takewhile, dropwhile, chain, accumulate, pairwise, batched

print(list(takewhile(lambda x: x < 4, [1, 2, 3, 5, 1])))
print(list(dropwhile(lambda x: x < 4, [1, 2, 3, 5, 1])))
print(list(chain([1, 2], "ab", (9,))))
print(list(accumulate([1, 2, 3, 4])))
print(list(accumulate([1, 2, 3, 4], max)))
print(list(pairwise([1, 4, 9, 16])))
print(list(batched(range(7), 3)))
[1, 2, 3]
[5, 1]
[1, 2, 'a', 'b', 9]
[1, 3, 6, 10]
[1, 2, 3, 4]
[(1, 4), (4, 9), (9, 16)]
[(0, 1, 2), (3, 4, 5), (6,)]
  • takewhile stops at the first failure: the 1 after the 5 is not taken. This makes it the right tool for endless streams.
  • accumulate with max gives the running maximum.
  • pairwise is handy for differences between neighbours: [b - a for a, b in pairwise(data)].
  • batched (3.12+) is the clean way to chunk a stream.

With an endless source, takewhile or islice provide the end:

from itertools import count

print(next(x for x in count(1) if x % 7 == 0 and x % 5 == 0))
print(list(takewhile(lambda x: x < 40, (n * n for n in count(1)))))
35
[1, 4, 9, 16, 25, 36]

The first finds the first number divisible by both 7 and 5. The second takes the squares until one reaches 40: it never makes 49. Chapter 17 returns to itertools in detail.

4. Measuring memory

You can see the saving yourself with the standard tracemalloc module. It reports the peak memory allocated by a piece of code:

import tracemalloc

def peak(fn):
    tracemalloc.start()
    fn()
    _, p = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return p

p_list = peak(lambda: sum([x * 2 for x in range(500000)]))
p_gen = peak(lambda: sum(x * 2 for x in range(500000)))
print(p_list > 100 * p_gen, p_gen < 20000)
True True

The list version needed more than a hundred times the memory of the generator version, and the generator stayed under 20 KB. (Run it yourself and print p_list and p_gen to see the real numbers on your computer.) Measuring beats guessing: tracemalloc.get_traced_memory() returns (current, peak) in bytes.

5. Pitfalls of lazy pipelines

1. One pass only

Every stage is a generator, so the whole pipeline can be used once. To run it again, build it again (call the functions again). To keep the results, put them in a list (section 6).

2. Errors appear late

A bad input may not cause an error until the item reaches a stage, which could be much later than where you built the pipeline. Example: a ValueError from int(...) shows up when the consuming loop runs, not when you wrote the line. Test stages on small data, and catch errors where you consume.

3. Order of side effects

Stages run interleaved: item 1 goes through everything before item 2 starts. The print lines in section 1 showed this. If your stages print, write or modify things, the output order will differ from what a step-by-step list version would give. Keep stages free of side effects when you can (lesson 11.8).

4. Partly used pipelines

If you stop early (with break, an exception or islice), a generator keeps its place and can be resumed (lesson 12.4):

def main():
    data = (n for n in range(3))
    try:
        for n in data:
            if n == 1:
                raise ValueError("stop")
    except ValueError as e:
        print("stopped at", e)
    print(list(data))

main()
stopped at stop
[2]

The loop stopped at 1, and the rest of the generator, 2, was still waiting.

5. Resources stay open

A generator reading a file keeps the file open until the generator finishes or is closed (chapter 15). For a pipeline that you may not finish, either use with inside the generator or call its .close() (lesson 12.5).

6. Hard to debug

You cannot look "inside" a generator the way you can print a list. To debug, take a few items with list(islice(stage, 5)) and look at them, or add a temporary stage that prints each item and passes it along:

def spy(items, label="item"):
    for item in items:
        print(label, item)
        yield item

Put spy(...) between two stages to see what flows through, and remove it when done.

6. When to make a list

Use a lazy pipeline when data is large, endless or processed once. Materialise (turn into a list) when:

Need Reason
use the results more than once a generator is empty the second time
index, slice, take len or sort needs all items (note sorted(...) itself builds a list)
the data is small a list is simpler
you must see all errors first a list forces all the work now

A good pattern: keep the pipeline lazy until the end, and call list(...) (or sum, max, ...) once on the final stage.

Worked example: sensor readings, in a lazy pipeline

A sensor sends readings as text lines, such as "21.5", with noise: blank lines, "ERR" and impossible values. Compute the average of the valid readings (between -50 and 60), the highest one, and the first reading above 30, without storing all the numbers.

from itertools import islice

raw = ["21.5", "", "ERR", "19.0", "99.9", "31.2", "  ", "22.8", "-70", "30.0"]

def clean(lines):
    return (l.strip() for l in lines if l.strip())

def numbers(lines):
    for l in lines:
        try:
            yield float(l)
        except ValueError:
            continue

def in_range(values, low=-50, high=60):
    return (v for v in values if low <= v <= high)

def readings(lines):
    return in_range(numbers(clean(lines)))

values = list(readings(raw))
print(values)
count = sum(1 for _ in readings(raw))
print(round(sum(readings(raw)) / count, 2), max(readings(raw)))
print(next((v for v in readings(raw) if v > 30), None))
print(list(islice(readings(raw), 2)))
[21.5, 19.0, 31.2, 22.8, 30.0]
24.9 31.2
31.2
[21.5, 19.0]
Stage Job
clean strips spaces and drops blank lines
numbers converts text to numbers, and skips text such as ERR
in_range drops impossible values (99.9 and -70)
readings(raw) builds a fresh pipeline each time it is called

Because readings(raw) builds a new pipeline for every question, each question gets a full stream. (Reusing one generator would give 0 the second time.) The readings are made up.

Common mistakes

  • Reusing a pipeline that has already been consumed.
  • Converting every stage to a list, which loses the memory advantage.
  • Debugging by guessing. Use islice and a spy stage.
  • Putting side effects in stages and being surprised by the order.
  • Forgetting that sorted, list and tuple consume everything.
  • Leaving files open in a generator that is never finished.

Key takeaways

  • A lazy pipeline chains generators; items flow one at a time, so memory stays small and early stopping saves work.
  • Building a pipeline does nothing; work happens when something consumes it.
  • itertools provides lazy tools: islice, takewhile, dropwhile, chain, accumulate, pairwise, batched and more.
  • Measure memory with tracemalloc instead of guessing.
  • A pipeline can be used once, errors appear late, and stages interleave; use a list when you need the data again, or a length, or an index.

Practice

1. What does building a pipeline of generator expressions do before you ask for values?

Show answer

Almost nothing. Only the first source iterable is looked at; no items are processed until something consumes the pipeline.

2. Take the first 5 items of any iterator it.

Show answer

list(itertools.islice(it, 5)).

3. What do takewhile(lambda x: x < 3, [1, 2, 5, 1]) and dropwhile(lambda x: x < 3, [1, 2, 5, 1]) give?

Show answer

[1, 2] and [5, 1]. takewhile stops at the first failure; dropwhile starts there.

4. Why can you not run the same pipeline object twice?

Show answer

Generators are used up after one pass. Build the pipeline again (or keep the results in a list).

5. Write the differences between neighbouring items of data using pairwise.

Show answer

[b - a for a, b in itertools.pairwise(data)] (Python 3.10 and later).

6. When should you convert a lazy result into a list?

Show answer

When you need to use the items more than once, take the length, index or slice them, or when the data is small enough that simplicity matters.