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.
- 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:
| Component | Pattern Used | Key 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_positive | Decorator + @functools.wraps | Preserve function metadata and forward return func(*args, **kwargs) |
Pre-Lab Watchouts Before You Code
- Mixing
returnandyield: Inparse_transactions,yieldemits each parsed tuple lazily; don't append to a list andreturn. - Skipping
boolinisinstance(val, (int, float)): In Python,boolis a subclass ofint(isinstance(False, int)isTrue, andFalse == 0 <= 0!). Always guard withnot isinstance(val, bool)so boolean flags aren't mistakenly rejected as<= 0. - Dropping the return value: Inside
wrapper(*args, **kwargs), always writereturn func(*args, **kwargs)—forgettingreturncausesrectangle_area(4, 5)to returnNone.
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:
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)).totals_by_category(records)— consumes any iterable of(customer, category, amount)tuples and returns a plaindictmapping each category to its rounded total (round(total, 2)), usingdefaultdict(float).
Step-by-Step Hint
- First call
cleaned = line.strip(). Ifnot cleaned or cleaned.startswith("#"): continue. - Unpack
customer, category, amount_str = cleaned.split(":")andyield (customer, category, float(amount_str)). - In
totals_by_category, convert the finisheddefaultdict(float)back to a standarddictwith rounded floats so callers receive clean JSON-friendly data.
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 (
intorfloat, excludingbool) before callingfunc. - Raises
ValueError("All numeric arguments must be > 0")if any numeric argument is<= 0.
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:
summary = totals_by_category(parse_transactions(RAW_LINES))parse_transactions(RAW_LINES)returns a suspended generator object—zero lines parsed yet.totals_by_category(records)starts itsfor _, category, amount in records:loop.- On each loop iteration, Python pulls one valid tuple from
parse_transactions, skips any#comment or blank line on the fly, addsamountintodefaultdict(float), and discards the string from memory before moving to the next line.
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.)