2. Iterators, Generators & Functional Tools

Practice Lab 1: Streaming Pipelines & Custom Decorators

Put Modules 1 and 2 into action: build a lazy generator pipeline with Counter/defaultdict and write reusable decorators tested with automated assert checks.

4 min readUpdated 2026-11-30
In This Lesson
  • Combine generator expressions, yield, and Counter into a streaming text pipeline
  • Build a working decorator that enforces input validation and preserves metadata
  • Verify every function against automated assert tests

Reading about generators and decorators only clicks once you build them under real constraints. In this lab, you will combine Modules 1 and 2 in the live Python sandbox—writing a lazy streaming pipeline and a reusable validation decorator backed by automated assert checks.

Why This Lab Matters: Architecture Overview

Real ETL pipelines and web APIs separate streaming/parsing from aggregation, and isolate cross-cutting validation inside decorators:

ComponentPattern UsedKey Design Rule
parse_transactions(lines)Generator (yield)Stream one record at a time; never build an intermediate list
totals_by_category(records)defaultdict(float)Accept any iterable (list, generator, file), not just a list
@require_positiveDecorator + @functools.wrapsPreserve function metadata and forward return func(*args, **kwargs)

Pre-Lab Watchouts Before You Code

3 Subtle Bugs to Avoid in This Lab
  1. Mixing return and yield: In parse_transactions, yield emits each parsed tuple lazily; don't append to a list and return.
  2. Skipping bool in isinstance(val, (int, float)): In Python, bool is a subclass of int (isinstance(False, int) is True, and False == 0 <= 0!). Always guard with not isinstance(val, bool) so boolean flags aren't mistakenly rejected as <= 0.
  3. Dropping the return value: Inside wrapper(*args, **kwargs), always write return func(*args, **kwargs)—forgetting return causes rectangle_area(4, 5) to return None.

Drill 1: Lazy Transaction Streamer (yield + defaultdict)

You are given raw transaction strings formatted as "customer:category:amount", plus occasional blank lines or # comments.

Write two functions:

  1. parse_transactions(lines) — a generator function (yield) that strips whitespace, skips blank lines and lines starting with #, splits valid lines by ":", and yields tuples (customer, category, float(amount)).
  2. totals_by_category(records) — consumes any iterable of (customer, category, amount) tuples and returns a plain dict mapping each category to its rounded total (round(total, 2)), using defaultdict(float).

Step-by-Step Hint

  • First call cleaned = line.strip(). If not cleaned or cleaned.startswith("#"): continue.
  • Unpack customer, category, amount_str = cleaned.split(":") and yield (customer, category, float(amount_str)).
  • In totals_by_category, convert the finished defaultdict(float) back to a standard dict with rounded floats so callers receive clean JSON-friendly data.
Python 3Drill 1: Streaming Parser & Category Totals
Output

Click “Run Code” to execute this snippet right in your browser.

Drill 2: Reusable @require_positive Decorator

Write a decorator require_positive that:

  • Uses @functools.wraps(func) to keep the wrapped function's __name__ and __doc__.
  • Inspects positional numeric arguments (int or float, excluding bool) before calling func.
  • Raises ValueError("All numeric arguments must be > 0") if any numeric argument is <= 0.
Python 3Drill 2: Validation Decorator
Output

Click “Run Code” to execute this snippet right in your browser.

How the Pieces Connect (Execution Trace)

Notice what happens when you pass the generator directly into the aggregator:

python
summary = totals_by_category(parse_transactions(RAW_LINES))
  1. parse_transactions(RAW_LINES) returns a suspended generator object—zero lines parsed yet.
  2. totals_by_category(records) starts its for _, category, amount in records: loop.
  3. On each loop iteration, Python pulls one valid tuple from parse_transactions, skips any # comment or blank line on the fly, adds amount into defaultdict(float), and discards the string from memory before moving to the next line.
Check Your Understanding

In Drill 2, why did @require_positive check not isinstance(val, bool) alongside isinstance(val, (int, float))?

Bonus Extension (Optional)

Once all assertions pass, try extending @require_positive in the sandbox so it also checks keyword arguments (kwargs.values())—for example, rectangle_area(4, height=-5)! (Hint: combine itertools.chain(args, kwargs.values()) in one clean loop.)

Lab 1 Completion Checklist

0/3 done