Python Master Course V2 — 110. Advanced Python Capstone: Streaming Analytics
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 11 · LESSON 110 OF 200
Advanced Python Capstone: Streaming Analytics
Study: 90–120 minutes · Prerequisites: Lessons 101–102, functions, classes, exceptions and tests.
Video lesson
Video not yet available. A verified video URL/player will be added when supplied.
Learning outcomes
Build a single-pass CSV analyzer; apply the explicit nonnegative amount and bounded precision contract; reconcile accepted and rejected logical records; propagate CSV and audit failures; own file lifetimes; and measure retained memory only after correctness checks.
Understand and apply: Advanced Python Capstone: Streaming Analytics
A streaming analytics pipeline composes lazy producers, validators, transformations, and aggregators. Error records must be counted, not silently discarded.
Define one auditable path from CSV to totals
This capstone combines lazy iteration, explicit validation, immutable events and a single-pass accumulator. The source schema is exactly type,amount. A receipt adds to receipts; a payment adds to payments; net is receipts minus payments. Amounts are nonnegative, at most 999999999.99 and written with zero, one or two decimal places. Zero is accepted. Signs, exponents, leading zeros such as 01, NaN and Infinity are rejected.
Invalid records produce Rejection events with logical record numbers and stable reasons. Wrong headers or malformed CSV syntax abort the run because the file cannot be reliably interpreted. Each successfully parsed data record increments exactly one accepted or rejected counter. Audit details go directly to an injected sink, so the analyzer does not retain an ever-growing error list.
Python file: lesson110.py
import csv
import re
from dataclasses import dataclass
from decimal import Decimal, localcontext
from io import StringIO
AMOUNT = re.compile(r"(?:0|[1-9][0-9]{0,8})(?:\.[0-9]{1,2})?")
MAX_RECORDS = 1_000_000
@dataclass(frozen=True)
class Transaction:
record: int
kind: str
amount: Decimal
@dataclass(frozen=True)
class Rejection:
record: int
reason: str
def events(source):
reader = csv.reader(source, strict=True)
if next(reader, None) != ["type", "amount"]:
raise ValueError("expected header: type,amount")
for number, cells in enumerate(reader, start=2):
if number - 1 > MAX_RECORDS:
raise ValueError("record limit exceeded")
if len(cells) != 2:
yield Rejection(number, "expected two cells")
continue
kind, text = (cell.strip() for cell in cells)
kind = kind.lower()
if kind not in {"receipt", "payment"}:
yield Rejection(number, "unknown type")
elif len(text) > 12 or AMOUNT.fullmatch(text) is None:
yield Rejection(number, "invalid amount")
else:
yield Transaction(number, kind, Decimal(text))
def analyze(source, audit):
accepted = rejected = 0
receipts = payments = Decimal("0.00")
with localcontext() as context:
context.prec = 28
for event in events(source):
if isinstance(event, Rejection):
audit(event)
rejected += 1
else:
accepted += 1
if event.kind == "receipt":
receipts += event.amount
else:
payments += event.amount
return accepted, rejected, receipts, payments, receipts - payments
sample = StringIO("\n".join([
"type,amount", "receipt,100.50", "payment,25.25", "receipt,bad",
"payment,-1", "receipt,0", "receipt,NaN"
]) + "\n")
def show_rejection(event):
print("Rejected:", event.record, event.reason)
accepted, rejected, receipts, payments, net = analyze(sample, show_rejection)
print("Accepted/rejected:", accepted, rejected)
print("Receipts/payments/net:", receipts, payments, net)
assert accepted + rejected == 6
# Boundary and failure cases use fresh sources.
def assert_raises(expected, action):
try:
action()
except expected:
return
raise AssertionError("expected exception was not raised")
zero = Decimal("0.00")
assert analyze(StringIO("type,amount\n"), lambda event: None) == (0, 0, zero, zero, zero)
for bad_header in ("", "amount,type\n"):
assert_raises(ValueError, lambda: analyze(StringIO(bad_header), lambda event: None))
boundary = analyze(StringIO("type,amount\nreceipt,999999999.99\npayment,0\n"), lambda event: None)
assert boundary == (2, 0, Decimal("999999999.99"), zero, Decimal("999999999.99"))
for invalid in ("01", "1e2", "+1", "-1", "1.234", "NaN", "Infinity", "1000000000.00"):
result = analyze(StringIO(f"type,amount\nreceipt,{invalid}\n"), lambda event: None)
assert result == (0, 1, zero, zero, zero)
rejections = [] # A tiny fixture, not the production audit sink.
result = analyze(StringIO("type,amount\nreceipt,1,extra\nreceipt\nother,1\n"), rejections.append)
assert result == (0, 3, zero, zero, zero)
assert [event.reason for event in rejections] == ["expected two cells", "expected two cells", "unknown type"]
def failed_audit(event):
raise RuntimeError("audit unavailable")
assert_raises(RuntimeError, lambda: analyze(StringIO("type,amount\nreceipt,bad\n"), failed_audit))
assert_raises(csv.Error, lambda: analyze(StringIO('type,amount\n"receipt,1\n'), lambda event: None))
# Exercise the record-limit branch cheaply, then restore the stated contract.
stated_limit = MAX_RECORDS
try:
MAX_RECORDS = 1
assert_raises(ValueError, lambda: analyze(StringIO("type,amount\nreceipt,1\nreceipt,1\n"), lambda event: None))
finally:
MAX_RECORDS = stated_limit
print("Capstone boundary checks passed")
from itertools import chain, repeat
import tracemalloc
for count in (1_000, 100_000):
lines = chain(["type,amount\n"], repeat("receipt,1.00\n", count))
tracemalloc.start()
try:
totals = analyze(lines, lambda event: None)
_, peak = tracemalloc.get_traced_memory()
finally:
tracemalloc.stop()
assert totals[:2] == (count, 0)
assert totals[2] == Decimal(count)
print(count, "records; peak traced bytes:", peak)
Expected output
Rejected: 4 invalid amount
Rejected: 5 invalid amount
Rejected: 7 invalid amount
Accepted/rejected: 3 3
Receipts/payments/net: 100.50 25.25 75.25
Capstone boundary checks passed
1000 records; peak traced bytes: <measured value>
100000 records; peak traced bytes: <measured value>
The parser emits one event at a time; the accumulator requests the next only after accounting for the current one. Validation happens before Decimal conversion. With at most one million records and the stated amount bound, a precision of twenty-eight comfortably represents the exact totals. If parsing or the audit sink fails, analyze raises instead of returning a completed summary; any audit already written belongs to a failed run.
Give files and audits explicit ownership
Python integration example: requires transactions.csv; creates a new rejected.csv
with open("transactions.csv", encoding="utf-8", newline="") as source:
with open("rejected.csv", "x", encoding="utf-8", newline="") as destination:
writer = csv.writer(destination)
writer.writerow(["record", "reason"])
totals = analyze(source, lambda event: writer.writerow([event.record, event.reason]))
print(totals)
Exclusive creation prevents overwriting an existing audit. Keep source and destination open until consumption finishes. This audit intentionally omits raw transaction data. Logical record numbers differ from physical line numbers when quoted fields span lines. Each individual CSV record must fit in memory; streaming avoids retaining the whole dataset, not an arbitrarily large single record.
Verify correctness before interpreting memory
Memory experiment included in the runnable capstone
The final part of the runnable capstone performs this memory experiment at 1,000 and 100,000 rows after the correctness checks.
Both record-count assertions must pass. Peak byte counts vary; record them rather than inventing expected measurements. repeat reuses a fixed record string, so the benchmark does not allocate the input dataset first. Test header-only input, wrong headers, ragged records, the maximum valid amount, three decimal places, nonfinite text, an audit failure and malformed quoting. Rejected rows must never contribute to totals.
Runnable capstone
The complete lesson110.py implementation, deterministic fixture, boundary checks and memory experiment appear in Understand and apply. The file integration example requires a prepared transactions.csv and creates rejected.csv exclusively. Run the complete program with Python 3.10+.
Guided practical project
Project: Build a CSV transaction streaming analyzer with rejected-row audit, Decimal totals, tests, and a memory benchmark.
Use the complete implementation and explicit contract in the worked explanation above. Reproduce its deterministic sample, test the stated boundary and failure cases, and explain the documented limitations before adapting it.
Common mistakes and debugging
- Adding abstraction without a demonstrated need.
- Hiding state or unexpected side effects.
- Assuming type hints replace validation.
- Ignoring resource cleanup or error propagation.
- Measuring performance on unrepresentative data.
- Failing to test boundary and error cases.
Debug by reproducing the smallest failing input, inspecting the traceback and intermediate values, then adding a regression test.
Practice with explained answers
Predict each result before opening the answer. Explain how the design handles both ordinary and boundary cases.
Why is a negative payment rejected rather than subtracted as a negative amount?
The schema represents direction with type and requires a nonnegative magnitude. A payment already contributes to the payments total, which is subtracted once when computing net. Allowing a negative payment without a separate policy could reverse direction twice.
What accounting invariant should hold for a completed run?
accepted + rejected equals the number of parsed data records, excluding the header. In the fixture it is three plus three equals six. A fatal CSV or audit error prevents a completed result, so partial counters must not be presented as a successfully reconciled file.
Why reject exponents and cap both amount and record count?
The textual amount contract is deliberately narrow and easy to audit. Magnitude and count bounds also bound the number of decimal digits needed in the accumulated totals, so the chosen Decimal precision is sufficient for exact arithmetic within this exercise’s domain.
What should a header-only source return?
It contains zero data records, so both counters remain zero and all totals remain Decimal("0.00"). This is a valid empty report. An entirely empty source has no required header and raises ValueError instead.
Worked answer: after the analyzer definitions
result = analyze(StringIO("type,amount\n"), lambda event: None)
assert result == (0, 0, Decimal("0.00"), Decimal("0.00"), Decimal("0.00"))
Does writing every rejection to a CSV file defeat bounded-memory processing?
Not when entries are written as events arrive using bounded buffering. Retaining them all in a Python list would grow with the rejection count. Disk usage still grows, so the operational contract should define audit retention and available storage.
Why can the memory benchmark compare one thousand with one hundred thousand rows fairly?
Both runs use the same parser and aggregation rules, a fresh lazy source and one fixed receipt string. Assertions verify the counts and totals. The printed peak measurements can then reveal retention growth without counting a prebuilt list of all input rows.
What happens if the audit callback raises during a rejected record?
The error propagates and analyze returns no completed summary. Previously written audit entries may remain. Mark that run as failed, keep its artifacts distinguishable from successful reports, and do not silently ignore the audit failure.
Mastery checkpoint
Explain the concept without notes, reproduce the core example, finish the project, run three tests and justify when the technique is appropriate. No account-synced completion or certification is claimed.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.