smartyfy.mrindigi.com

Python Master Course V2 — 102. Generators and Lazy Data Pipelines

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 11 · LESSON 102 / 200

Generators and Lazy Data Pipelines

Advanced Python · Estimated study 90–120 minutes · Prerequisites: Lesson 101 (iterators), functions, loops, exceptions and files.

Course hub · Lesson 101

Video lesson

Video not yet available. A verified video URL or embedded player can be placed here when supplied.

Learning outcomes

  • Explain how yield suspends a function and retains local state.
  • Differentiate generators, generator expressions and eager collections.
  • Build lazy map/filter/aggregate pipelines and identify single-pass hazards.
  • Use yield from and close() appropriately.
  • Stream large files with bounded memory and robust validation.
  • Test output, exhaustion and error behavior.

1. How generators work

A generator function contains yield. Calling it creates a generator object without executing the function body immediately. Each next() resumes execution until the next yield, preserving local variables and instruction position. Returning or reaching the end raises StopIteration to the consumer. A generator is an iterator and is normally one-pass.

Generators are especially useful for reading large files, parsing event streams, filtering records, and producing potentially unbounded sequences. Their advantage is incremental processing: the pipeline can process one value without retaining all previous values. This does not automatically make execution faster; it trades eager allocation for deferred work.

Backpressure: downstream consumers request values at their own pace. Avoid converting huge or infinite generators into lists. Exceptions from the producer occur when the generator is advanced, not necessarily when created.

2. Progressive runnable examples

Requires Python 3.10+. Each example is independent. Save as a .py file and run with python or python3. Expected output is shown after each example.

Example 1 — Yield and state

def countdown(n):
    while n > 0:
        yield n
        n -= 1
print(list(countdown(3)))
[3, 2, 1]

Each yield pauses the function while keeping n available for the next iteration.

Example 2 — Execution is deferred

def produce():
    print("started")
    yield 10
    print("resumed")
    yield 20
g = produce()
print("created")
print(next(g))
print(next(g))
created
started
10
resumed
20

Calling produce() creates the generator; the body begins on the first next().

Example 3 — Generator expressions

values = (x*x for x in range(5) if x%2 == 0)
print(sum(values))
print(list(values))
20
[]

sum consumes the generator. A second traversal produces no items.

Example 4 — yield from

def flatten(groups):
    for group in groups:
        yield from group
print(list(flatten([[1,2],[],[3]])))
[1, 2, 3]

yield from delegates iteration to another iterable, preserving order.

Example 5 — Lazy pipeline

rows = ["10", "bad", "20", "-5"]
def valid_numbers(source):
    for row in source:
        try:
            yield int(row)
        except ValueError:
            continue
print(sum(x for x in valid_numbers(rows) if x > 0))
30

For real reconciliation workflows, log invalid records rather than silently skipping them; this simplified example illustrates filtering only.

Example 6 — Bounded consumption

from itertools import count, islice
print(list(islice((n*n for n in count()), 5)))
[0, 1, 4, 9, 16]

islice prevents accidental unbounded materialization.

Understand and apply: Generators and Lazy Data Pipelines

Scenario: A report contains many CSV rows with a type (receipt or payment) and an amount. Process rows lazily, track valid totals and report malformed records. Never silently treat invalid amounts as zero.

Follow one record through the pipeline

A generator suspends at yield with its local state intact. The consumer drives progress: requesting one result may make an upstream parser read several rejected or filtered records. Creating a generator does not run its body, so schema errors can appear at the first next() rather than at the function call. Keep exception handling around consumption, and use return to finish a generator instead of explicitly raising StopIteration.

The transaction parser needs separate policies for an invalid file schema and an invalid record. A missing or reordered header aborts this example. A well-formed CSV record with missing cells, extra cells, an unknown type or a bad amount becomes an error event. Record numbers below count logical CSV records; quoted multiline fields mean they are not always physical file line numbers.

Python example

import csv
from decimal import Decimal, InvalidOperation
from io import StringIO

def parsed_transactions(lines):
    reader = csv.DictReader(lines, strict=True)
    if reader.fieldnames != ["type", "amount"]:
        raise ValueError("expected header: type,amount")
    for record_number, row in enumerate(reader, start=2):
        try:
            if None in row or any(row[key] is None for key in ("type", "amount")):
                raise ValueError("expected exactly two cells")
            kind = row["type"].strip().lower()
            if kind not in {"receipt", "payment"}:
                raise ValueError("unknown type")
            try:
                amount = Decimal(row["amount"].strip())
            except InvalidOperation:
                raise ValueError("invalid decimal amount") from None
            if not amount.is_finite() or amount < 0:
                raise ValueError("amount must be finite and nonnegative")
        except ValueError as error:
            yield ("error", record_number, str(error))
        else:
            yield (kind, record_number, amount)

sample = StringIO("\n".join([
    "type,amount", "receipt,100.50", "payment,25.25", "receipt,bad"
]) + "\n")
receipts = payments = Decimal("0")
accepted = rejected = 0
for kind, record, value in parsed_transactions(sample):
    if kind == "error":
        rejected += 1
        print("Rejected record:", record)
    else:
        accepted += 1
        if kind == "receipt":
            receipts += value
        else:
            payments += value
print("Totals:", receipts, payments, receipts - payments)
print("Accepted/rejected:", accepted, rejected)

Expected output

Rejected record: 4
Totals: 100.50 25.25 75.25
Accepted/rejected: 2 1

The join expression inserts real newline characters into the fixture. Literal letter n separators would create one malformed header instead. Missing cells are validated before Decimal receives a value, avoiding Decimal(None). Malformed CSV syntax still raises csv.Error and aborts consumption; do not publish partial totals as a completed reconciliation. This introductory parser allows arbitrary decimal precision; the capstone will add a bounded, two-decimal monetary contract.

Close an interrupted producer deliberately

Python example

from contextlib import closing

def readings():
    try:
        yield 10
        yield 20
    finally:
        print("producer closed")

with closing(readings()) as values:
    print(next(values))
print("consumer finished")

Expected output

10
producer closed
consumer finished

A break alone does not guarantee immediate cleanup of a still-referenced generator. closing calls close() when the block exits, causing an already-started generator to run its finally block. Prefer owning an input file in an outer with block and fully consuming the pipeline inside that block. Closing a generator that has never started cannot run its unentered body.

Keep rejected-record counts in memory and stream detailed errors to an audit destination. An ever-growing errors list defeats bounded-memory processing even when the producer is lazy. Test a header-only file, a missing amount, an extra cell, NaN, Infinity, an unknown type, exhaustion and early closure. Each accepted or rejected logical record should be accounted for exactly once.

4. Common mistakes and debugging

  • Expecting generator code to run at creation rather than iteration.
  • Trying to reuse an exhausted generator.
  • Calling list() on an infinite generator.
  • Assuming lazy evaluation guarantees constant memory after downstream accumulation.
  • Suppressing parse errors without reporting rejected records.
  • Confusing yield with return: yield emits a value and pauses; return ends the generator.

5. Exercises and model answers

What does list(x for x in range(3)) return?

Answer: [0, 1, 2].

Why does a second list(g) often return []?

Answer: the generator was exhausted on the first pass.

Write a generator for even numbers below n.

Model: (x for x in range(n) if x % 2 == 0).

How do you limit an infinite sequence?

Model: itertools.islice(sequence, limit).

Extend the project to count accepted records.

Model: increment a counter in the receipt/payment branches.

Practice with explained answers

Predict each result before opening the answer. Trace state changes and explain the contract as well as the output.

Why can a bad header fail only when iteration starts?

parsed_transactions is a generator function. Calling it creates a suspended generator; the DictReader and header check run on the first advancement. Wrap the for loop or list() consumption in the exception handler.

What is wrong with type,amountnreceipt,100.50n as a fixture?

The letter n is ordinary data. It does not separate CSV records. Use a Python newline escape or join a list of record strings with a newline; inspect the rendered source after publishing to ensure the backslash is preserved.

What happens to a row containing only receipt?

DictReader supplies None for the missing amount. The explicit cell check converts this into one error event before attempting Decimal conversion. The record is rejected and counted; it is not treated as a zero-value receipt.

How many values remain after sum(g) consumes a generator?

None remain if sum reaches normal exhaustion. To calculate several aggregates, update them together in one pass or create a fresh generator from a reusable source. Reusing the same exhausted object produces no new values.

Worked answer

g = (value * 2 for value in range(3))
print(sum(g))
print(list(g))

Expected output

6
[]
Why use closing around an early-stopped generator?

It makes the owner call close() at a predictable scope boundary. For a generator suspended inside try/finally, that runs cleanup even when only the first value was requested. This does not close unrelated resources the generator never acquired.

Does a generator plus errors.append guarantee bounded memory?

No. The generator is incremental, but the consumer retains every rejected record. Count rejections and write audit entries as they occur, or retain a fixed-size sample alongside the total count.

6. Five-question self-check with explanations

When does a generator body start executing? A when advanced; B when defined; C when imported; D never.

Answer A. Calling the generator function creates a lazy object.

What does yield do? A always terminate; B emit and suspend; C delete variables; D start a thread.

Answer B. Local state is retained.

What is a typical generator limitation? A cannot loop; B cannot hold values; C one-pass consumption; D must use a database.

Answer C. Generators usually cannot be rewound.

How do you safely sample an infinite generator? A list(g); B tuple(g); C sum(g); D islice(g, n).

Answer D. It bounds consumption.

What should happen to malformed financial rows? A report them; B silently ignore; C invent amounts; D overwrite source.

Answer A. Reconciliation must remain auditable.

7. Mastery checkpoint

Explain generator suspension, demonstrate one-pass behavior, implement a streaming parser, handle malformed records and test at least five boundary scenarios. These are learning criteria, not account-synced completion records.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.