A feed supplies records incrementally so a consumer can request and process a limited portion of the source.
Combine row validation, batching and lazy consumption, then prove that the feed stops reading when the consumer has enough.
Turn chunks of sensor text into validated records and fresh batches, stopping when the caller has enough. This combines iterator consumption, suspended generator state, and the object-sharing rules from the data-model section. The challenge is to preserve records across chunk boundaries and keep counts honest when only part of the input has been examined.

The shape of the feed
Four stages, and a limit on the end:
For a real streamed source, working storage depends on chunk size, longest
partial line, and batch size, including temporary split results. This exercise
receives an already-loaded text string and collects batch summaries in its
result, so total memory also includes that input and output. A generator does
not remove storage owned by its caller.
Preparing this topic’s interactive investigation…
Judge each row without taking the whole feed down
records(lines, tally) does three jobs: skip blank lines silently, skip
the first non-blank line (the header), and turn each remaining line into
(sensor, reading) — or count it as bad. A row is bad when it doesn't have
exactly two fields, or float() refuses the reading. The naive version
trusts the file, and the first broken row takes the whole feed down with
it:
ValueErrorRun it and read which row killed it. Then make records skip and count both kinds of bad row instead of raising.
One bad row in ten million shouldn't stop a nightly run — it should show up
as a count someone can glance at in the morning. That's what tally is
for: a plain dict the stages write their counts into, so downstream stages continue receiving a uniform record type. A generator
can yield mixed types, but doing so would force every consumer to distinguish
records from control messages.
Batch pump readings without a stale reference bug
batched(items, n) collects items into lists of n, yields each list the
moment it's full, and flushes the leftovers at the end:
def batched(items, n):
batch = []
for item in items:
batch.append(item)
if len(batch) == n:
yield batch
batch = []
if batch:
yield batch
print(list(batched(range(7), 3)))One line looks like it could be tidier: batch = [] makes a new list
every time. It's tempting to write batch.clear() and reuse one list
instead — this is the real mistake, and it doesn't raise anything, it just
quietly corrupts the output:
def batched(items, n):
batch = []
for item in items:
batch.append(item)
if len(batch) == n:
yield batch
batch.clear()
print(list(batched(range(4), 2)))This is the one real hazard of a generator's parked frame: it still holds
references to whatever it yielded, and if it mutates them after the
yield, the consumer sees the change. (Python 3.12's itertools.batched
yields tuples and never has this problem — writing it yourself once is how
you learn to spot the bug.)
Prove the feed actually stops early
The last stage is islice(batches, max_batches) — lesson 03's take, from
itertools. islice(x, None) means no limit, so one line serves both
modes. When islice has its last batch it stops asking, batched stays
parked, records stays parked, and the next chunk is never read.
chunks_read in the tally is the proof — step through a small run with a
limit of one batch and watch the count stop short of the end of the text:
Three lines were enough, so three chunks of five were read, not all five.
The third line, b,2, only became complete in the third chunk — on the
real file that's the difference between reading a few kilobytes and reading
all of it. Double the rows in the file and an eager version (read the
whole thing into a string, parse every row into a list) doubles its memory;
the stages' working storage can remain bounded if line and batch sizes are
bounded. The in-memory text and collected summary list in this exercise still
grow; a file-to-sink version must avoid retaining those too.
Audit the boundaries before joining the stages
This capstone combines the object-sharing lesson with generator suspension: yielding a batch transfers a reference, not a snapshot. The producer must start a new list before building the next batch so a consumer's earlier result remains stable. A tuple would prevent changing the batch's slots, but mutable objects inside it would still be shared.
Use these checkpoints to locate a wrong count:
| Boundary | Evidence to inspect |
|---|---|
| Chunk → line | A separator split between chunks still produces one complete line |
| Line → record | Blanks do not consume the “first non-blank header” rule |
| Record → batch | A full batch is yielded before asking for another record |
| Limit → source | Zero requested batches means zero chunk pulls |
chunks_read measures chunks obtained, not records fully processed. The final
chunk may already contain characters after the last requested batch. Likewise,
skipped covers only visited rows; it is not a quality report for the entire
file when a limit stopped the run.
This is a deliberately restricted comma-separated format: fields cannot contain
quoted commas or embedded newlines. A general CSV reader needs csv.reader and
a compatible streaming boundary. float("nan") and float("inf") also succeed;
the current exercise accepts whatever float accepts. A sensor contract that
requires finite readings needs an additional math.isfinite check.
Transfer the feed to an alert that stops on the first high reading. Predict
whether a malformed row after that alert should affect skipped, then test a
chunk boundary that puts both rows in one chunk. Distinguish reading bytes from
judging records.
What you're given, and what you write
The starter already contains chunks(text, size, tally) (reads size
characters at a time, counting tally["chunks_read"]) and
lines_from_chunks(chunks) (lesson 02's line feed). You write three
things:
records(lines, tally)— skip blanks, skip the header, yield(sensor, reading)as afloat, count every bad row intally["skipped"].batched(items, n)— lists ofn, each yielded the moment it's full, a fresh list every time, leftovers at the end.stream_records(text, chunk_size, batch_size, max_batches)— chain the stages, stop withislice, summarise each batch as[count, total rounded to 2 places], and return{"batches": [...], "skipped": n, "chunks_read": n}.
Because the stages are lazy, skipped only counts the bad rows the feed
actually reached — rows it never read were never judged.
🎯 Your turn
With the text "sensor,reading\npump-1,4.5\npump-2,oops\npump-1,5.5\n\npump-3,1.0\npump-1\npump-2,2.0\n",
chunks of 8 and batches of 2:
max_batches = None→{"batches": [[2, 10.0], [2, 3.0]], "skipped": 2, "chunks_read": 10}max_batches = 1→{"batches": [[2, 10.0]], "skipped": 1, "chunks_read": 7}, which stops on the chunk that completespump-1,5.5and never reaches the rest.
Hint: yield a batch straight after the append that fills it, not at
the top of the next pass. That way the feed never pulls a record it doesn't
need.
Press ▶ Run, then ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write the generator chunks(text, size), which yields text in pieces of size characters, the last one possibly shorter. It stands in for calling f.read(size) until the file is used up. chunk_list(text, size) returns the list.
Write the generator records(lines, tally): skip blank lines, skip the header (the first non-blank line), yield (sensor, reading) with the sensor stripped and the reading a float, and add 1 to tally["skipped"] for every row without exactly two fields or with a reading float() refuses. parse_report(lines) (already written) collects the result.
This batched(items, n) uses batch.clear() to reuse one list, and every batch comes out wrong. Fix it so each batch is a list that never changes after it has been yielded. batches(items, n) returns them all.
A generator is single-use, but Quarry's report wants to walk the same file twice. Write ReadingFeed(text, size), an iterable whose __iter__ is a generator function (it contains yield). Each loop starts a fresh pass: chunk the text, rebuild lines with lines_from_chunks, skip blanks and the header, and yield each good reading as a float, skipping bad rows. feed_twice sums it twice.
The night watch only needs the first reading above a threshold, and then it should stop reading the file. chunks, lines_from_chunks and records are provided. Write early_alarm(text, size, threshold), which returns {"first": [sensor, reading] or None, "chunks_read": n}.
A teammate reviewing the feed says: "This is over-engineered. Just do open(path).read().splitlines() and loop over the list. Memory is cheap." Reply to them. Say when they're right, when the streaming feed matters, and what the streaming version costs you in return.