Module 01A: Projects

Foundations6 projects0 of 6 complete

Starter projects are guided step by step and suit freshers. Stretch projects are open-ended, add production concerns, and suit experienced readers.

Six projects: three starters and three stretches (the program port is optional). Every one is completely keyless — pure Python standard library, offline, deterministic, no API key, no account and no paid service anywhere. There is nothing to install beyond Python 3.11+ itself:

bash
uv python install 3.13     # or any Python 3.11+; see 01A.1 §2.1
uv run python --version    # check what you're running

Run scripts with python3 file.py or uv run file.py. Two optional quality gates download tools on demand via uvx (still free, still no project setup): uvx ruff check . and uvx mypy . — 01A.10 §5.2 and §6.4 show how.

Every project ships its own data. Each one gives you a small fixture to create inline (a CSV, a JSON file, a log generator) — no private data, no downloads. The running example is the module's support-ticket triage toolkit: the triage package evolves through the lessons and reaches its canonical form in 01A.10's appendix, which Starter A assembles. Field names drift slightly between lesson iterations (ticket_id vs id, Priority direction); when in doubt the appendix is the final word.


Starter

Starter: Ticket triage CLI#

Goal: Assemble the triage package the eleven lessons have been building into a real, runnable command-line tool — load tickets from CSV or JSON, classify them with keyword rules, summarise with Counter, write JSON and CSV reports — then extend it with one feature of your own.

What you'll practise:

Setup: Python 3.11+ as above. Create a working folder triageproj/ — everything lives inside it:

text
triageproj/
├── data/
│   ├── tickets.csv
│   └── tickets.json
├── triage/
│   ├── __init__.py
│   ├── __main__.py
│   ├── models.py
│   ├── rules.py
│   ├── io.py
│   ├── report.py
│   └── cli.py
└── README.md

Steps:

  1. Create the data files. Save data/tickets.csv and data/tickets.json exactly as 01A.10 Appendix A.8 prints them — twelve CSV rows (the last one deliberately missing its subject) and three JSON items (one deliberately missing its subject).

  2. Write the package. Copy the seven files from Appendix A.1–A.7 into triage/ exactly as printed — __init__.py, __main__.py, models.py, rules.py, io.py, report.py, cli.py. Type them yourself rather than copy-pasting if you're a fresher; the typing is the lesson. If you assembled an earlier triage/ version in 01A.7 instead, replace it with this final form — the vocabularies differ.

  3. Run it. From inside triageproj/:

    bash
    python3 -m triage

    The default input is data/tickets.csv relative to your current directory, not the package — cd triageproj first (the 01A.9 §1.1 trap).

  4. Run the JSON input. python3 -m triage --input data/tickets.json --outdir reports-json — same pipeline, different loader, chosen by file extension.

  5. Read the warnings. The CSV run prints one WARNING triage.io: skipping row 13 and the JSON run skips its bad item — find the two bad rows in your data files and confirm the loader's problem strings name the right lines.

  6. Add --dry-run. Following 01A.9 §6.3's habit, add a flag that prints the summary table but skips save_report_json/save_report_csv. Prove it: run with and without the flag and diff reports/.

  7. Add JSONL input. Write load_tickets_jsonl(path) in io.py using the streaming pattern from 01A.9 §3.5 (parse each line independently, collect per-line problems, never hold the whole file), wire it into load_tickets for .jsonl, and create a data/tickets.jsonl by converting the JSON fixture one object per line.

  8. Prove it with asserts. Add test_triage.py with plain assert functions (the pre-pytest habit from 01A.8 Part 8): classify_ticket routes "charged twice" to billing, summarise counts match a hand-computed fixture, and loading the bad-row CSV returns 11 tickets plus 1 problem. Run it with python3 test_triage.py — no framework needed.

  9. Optional polish. Run uvx ruff check triage/ and uvx ruff format --check triage/ (01A.10 §6.4), then uvx mypy triage/ (01A.10 §5.2) and fix what they flag.

Verify it, and what you should see:

bash
cd triageproj
python3 -m triage
python3 -m triage --input data/tickets.json --outdir reports-json
python3 test_triage.py

The CSV run's real output (produced by the lesson's own listing — deterministic, your output should match exactly):

text
WARNING triage.io: skipping row 13: missing id or subject
Loaded 11 tickets from data/tickets.csv
Skipped 1 bad rows:
  - line 13: missing id or subject
Urgent or high, still open: 4
  T-1001 [URGENT] open: App crashes on login (acme)
  T-1004 [HIGH] in_progress: Password reset broken (umbrella)
  T-1007 [URGENT] in_progress: API returns 500 on /v1/search (oscorp)
By status:
  closed       1
  in_progress  2
  open         7
  resolved     1
By category:
  billing    2
  bug        4
  feature    2
  other      1
  question   2
Wrote reports/report.json and reports/report.csv

The JSON run loads 2 tickets and skips 1 (the item with an empty subject). Your test_triage.py should print nothing on success — add a final print("all checks passed") if you like the confirmation. reports/report.json should contain the Summary fields plus a tickets array; report.csv one enriched row per ticket including the category column.

Done when:

  • python3 -m triage runs from triageproj/ and produces the table above plus reports/report.json and reports/report.csv.
  • The JSON input path works and its bad item is reported, not fatal.
  • --dry-run prints the same summary and writes no files.
  • .jsonl input loads through the new streaming loader.
  • test_triage.py passes with plain asserts.
  • Your README.md explains the layout and the run commands in your own words.

Stretch ideas: Add an escalate subcommand that applies Ticket.escalate() to every urgent-open ticket and writes the result back (01A.6 §1.6/Part 6). Add a second Classifier implementation behind the Protocol seam from 01A.6 §2.5 — e.g. the LengthClassifier idea — and a --classifier flag. Persist tickets to the JSON key-value store from the Stretch project below instead of rewriting reports.

Common problems:

  • ModuleNotFoundError: No module named 'triage' — you ran from the wrong directory or the folder isn't next to the script; cd into triageproj/ (01A.7 §3 covers sys.path).
  • FileNotFoundError on data/tickets.csv — the default path is relative to your current directory; run from triageproj/ or pass --input.
  • CSV rows parse but every priority looks wrong — CSV gives strings; the appendix's _row_to_ticket upper-cases the value and then looks it up by member name (Priority["URGENT"]), so urgent works but a number like 1 or a word like critical is reported as unknown priority.
  • The bad row isn't skipped — check you used the appendix io.py (it returns (tickets, problems)), not an earlier lesson's loader.
  • Confusion over Priority direction — in the appendix URGENT = 1, lower means more urgent; 01A.6's earlier toolkit had it the other way. The appendix is canonical.

Starter

Starter: Text toolkit#

Goal: Build a small textkit package that does the four text jobs AI engineers run constantly: count word frequencies, turn messy titles into URL slugs, extract dates/emails/IDs from free text with regular expressions, and inspect any string's Unicode code points and UTF-8 bytes.

What you'll practise:

  • String methods, f-strings, formatting and str.join (01A.2 Part 2, Part 3)
  • The slugify recipe — NFKD, ASCII-fold, regex cleanup (01A.2 §6.2)
  • Regular expressions: named groups, findall/finditer, raw strings, the ten practical patterns (01A.2 §5.1, §5.2, §5.5, §6.3)
  • Unicode and encodings: code points, unicodedata.name, NFC/NFD, str.encode/bytes.decode, why len isn't tokens (01A.2 Part 4, §4.7)
  • Counter and sorting with key= (01A.4 §4.8)
  • Packaging the functions into a textkit/ package with a python -m textkit CLI (01A.7 Part 2, §5.9)
  • Type hints on the public functions (01A.10 Part 2)

Setup: Python 3.11+ as before. Create textkitproj/ with this layout:

text
textkitproj/
├── textkit/
│   ├── __init__.py
│   ├── __main__.py
│   ├── words.py
│   ├── slug.py
│   ├── extract.py
│   ├── unicode_inspect.py
│   └── cli.py
└── sample.txt

Steps:

  1. Create sample.txt. A small mixed document — paste this exactly:

    text
    Café Déjà Vu: 2026 — Product Launch Notes
    Contact: Priya Nair <priya.nair@example.com>, backup omar+haddad@mail.example.org
    Ticket refs: TKT-1042 and TKT-2077. Deadline 2026-11-30, review on 2026-12-05.
    Amounts: $1,090.00 USD and €42.50. Order id ORD-8821 ships 2026-11-08.
    Emoji check: 🚀 works, and naïve café résumé co-exist.
  2. words.py — word frequencies. Write word_freq(text: str, top: int | None = None) -> list[tuple[str, int]]: lowercase, extract words with re.findall(r"[a-z0-9']+", text.lower()), count with Counter, return most_common(top). Keep punctuation out by not matching it — do not strip it afterwards.

  3. slug.py — the slugifier. Copy slugify from 01A.2 §6.2 verbatim, typed. Then test it on the sample's first line and three of your own titles, including one with accents and one with emoji (expect the emoji title to produce a short or empty slug — that's the documented non-Latin-script caveat).

  4. extract.py — field extraction. Write one compiled regex per field with named groups, and extract_fields(text: str) -> dict[str, list[str]] that returns every match of each pattern: ISO dates \d{4}-\d{2}-\d{2}, loose emails [\w.+-]+@[\w-]+\.[\w.]+, ticket IDs TKT-\d+, order IDs ORD-\d+. Base the patterns on §5.5's practical patterns; use finditer and handle zero matches gracefully (empty list, not None).

  5. unicode_inspect.py — the Unicode inspector. Write inspect_text(text: str) -> list[dict[str, object]] returning one record per character: the character itself, ord(c) code point, unicodedata.name(c, "<unknown>"), UTF-8 byte length via len(c.encode("utf-8")), and the NFC/NFD normalised forms where they differ. Print it as a table from the CLI. This is the tool that makes §4.7's "characters ≠ tokens" concrete.

  6. cli.py + __main__.py. An argparse CLI with four subcommands — words FILE [--top N], slug TEXT, extract TEXT, unicode TEXT — dispatching to the modules, plus __init__.py re-exporting the public functions and __main__.py calling cli.main() so python -m textkit works (01A.7 §2.5).

  7. Verify and extend. Run every subcommand on sample.txt, then add one feature: a clean subcommand that NFC-normalises, strips format characters and collapses whitespace — the normalize_text recipe from 01A.2 §7.3.

Verify it, and what you should see:

bash
cd textkitproj
python3 -m textkit words sample.txt --top 8
python3 -m textkit slug "Café Déjà Vu: 2026 — Product Launch Notes"
python3 -m textkit extract "see TKT-1042 and ORD-8821, due 2026-11-30, mail priya.nair@example.com"
python3 -m textkit unicode "café 🚀"
Example output · illustrative27 lines
$ python3 -m textkit words sample.txt --top 8
   4 2026
   3 and
   2 caf
   2 priya
   2 nair
   2 example
   2 tkt
   2 11

$ python3 -m textkit slug "Café Déjà Vu: 2026 — Product Launch Notes"
cafe-deja-vu-2026-product-launch-notes

$ python3 -m textkit extract "see TKT-1042 and ORD-8821, due 2026-11-30, mail priya.nair@example.com"
dates:    ['2026-11-30']
emails:   ['priya.nair@example.com']
tickets:  ['TKT-1042']
orders:   ['ORD-8821']

$ python3 -m textkit unicode "café 🚀"
char  codepoint  name                     utf8  nfc   nfd
c     U+0063     LATIN SMALL LETTER C      1     c     c
a     U+0061     LATIN SMALL LETTER A      1     a     a
f     U+0066     LATIN SMALL LETTER F      1     f     f
é     U+00E9     LATIN SMALL LETTER E...   2     é     e + ́
(space) U+0020   SPACE                     1     (space) (space)
🚀    U+1F680    ROCKET                    4     🚀    🚀

Note what the inspector shows: é is one code point in NFC but two code points (e + combining acute) in NFD — same visual, different len() — and 🚀 is one code point but four UTF-8 bytes and two UTF-16 code units (why JS "🚀".length === 2). These are exactly the traps 01A.11 maps for switchers.

Done when:

  • All four subcommands run from textkitproj/ via python -m textkit.
  • slug produces cafe-deja-vu-2026-product-launch-notes on the sample title.
  • extract finds all four field kinds in the test string and returns empty lists (not errors) for absent kinds.
  • unicode shows the NFC/NFD difference for é and the byte/code-point counts for 🚀.
  • clean normalises the sample text (NFC, no format chars, single spaces).
  • Every public function has a type hint and a one-line docstring.

Stretch ideas: Add a diff TEXT1 TEXT2 subcommand using difflib.unified_diff (01A.2 §6.5). Add a template subcommand using string.Template (01A.2 §6.4). Add word-frequency by document section using splitlines (01A.2 §2.5).

Common problems:

  • words shows caf instead of café — correct for the prescribed regex: [a-z0-9']+ is ASCII-only, so the accented é ends the match. It is a good moment to try \w+ (Unicode-aware) and compare the counts.
  • words counts punctuation as words — your regex is matching non-word characters; [a-z0-9']+ excludes them by construction.
  • slug returns mojibake or empty for non-Latin titles — expected; NFKD+ASCII only handles Latin scripts (01A.2 §6.2 says so).
  • extract misses the email — check your pattern against omar+haddad@mail.example.org (the + and multi-part domain); test each pattern standalone in the REPL before wiring the CLI.
  • Catastrophic backtracking on a pathological input — your patterns are linear; if you nested quantifiers like (\w+)+, read 01A.2 §5.3 before shipping it.
  • python -m textkit fails with No module named 'textkit' — run from textkitproj/, the folder containing textkit/.

Starter

Starter: Personal finance CSV analyser#

Goal: Read a bank-export-style CSV of transactions, validate and convert it safely (money as Decimal, never float), aggregate spending by category and month with defaultdict/Counter, and write a summary report — the same collect-errors-at-the-boundary pattern the triage CLI uses.

What you'll practise:

Setup: Python 3.11+ as before. Create finance/ with finance.py and transactions.csv.

Steps:

  1. Create transactions.csv. A small export with one deliberately bad row — paste exactly:

    csv
    date,description,category,kind,amount
    2026-10-03,Whole Foods Market,groceries,expense,84.20
    2026-10-05,Salary deposit,income,income,2500.00
    2026-10-07,Electric bill,utilities,expense,132.45
    2026-10-09,Movie night,entertainment,expense,28.50
    2026-10-12,Whole Foods Market,groceries,expense,61.10
    2026-10-15,Bus pass,transport,expense,45.00
    2026-10-18,Fuel station,transport,expense,52.30
    2026-10-21,Salary deposit,income,income,2500.00
    2026-10-24,Pharmacy,health,expense,not-a-number
    2026-10-26,Pharmacy,health,expense,19.99
    2026-10-28,Electric bill,utilities,expense,128.00
  2. load_transactions(path) in finance.py: open with newline="", encoding="utf-8", iterate csv.DictReader with enumerate(..., start=2), convert amount via Decimal(row["amount"]) (catch InvalidOperation/ValueError per row), validate kind in ("income", "expense") and date shape, and return (transactions, problems) — a list of dataclass Transaction records plus "line N: reason" strings, exactly the 01A.8 Part 9 pattern.

  3. Aggregate. summarise(transactions) returns a dict: count, income_total, expense_total, net, by_category (expense totals per category, Decimal throughout), by_month (per YYYY-MM expense totals), and top_expense (the single largest). Use defaultdict(Decimal) and Counter — but note Counter sums numbers, so for Decimal totals prefer defaultdict accumulation; use Counter for counts (01A.4 §4.8).

  4. Report. Print a console table (category, total, count — sorted by total descending via sorted(..., key=lambda kv: kv[1], reverse=True)), and write report.json atomically (01A.9 §2.5) with json.dumps(..., default=str) — Decimal isn't JSON-native, so serialise as strings to keep cents exact, and say so in a comment.

  5. Verify by hand. Before running, compute the expected totals yourself: income 5000.00, expenses 551.54, net 4448.46; groceries 145.30, utilities 260.45, transport 97.30, entertainment 28.50, health 19.99; one bad row skipped. Your program's output must match — if it doesn't, the bug is in your code, not the arithmetic.

Verify it, and what you should see:

bash
cd finance
python3 finance.py transactions.csv
Example output · illustrative17 lines
Loaded 10 transactions from transactions.csv
Skipped 1 bad rows:
  - line 10: amount is not a number: 'not-a-number'

income_total   5000.00
expense_total   551.54
net            4448.46

By category (expenses):
  utilities      260.45  (2)
  groceries      145.30  (2)
  transport       97.30  (2)
  entertainment   28.50  (1)
  health          19.99  (1)

Top expense: Electric bill — utilities — 132.45 on 2026-10-07
Wrote report.json

report.json contains the same numbers as strings ("260.45", not 260.45) plus the skipped-row list. Its by_month table has a single entry, "2026-10": "551.54", because every expense in the fixture is from October 2026. float happens to print the same totals on this small fixture, so do not use the output to check your types: assert isinstance(total, Decimal) in a test instead, because float drift appears on other data (01A.2 §1.6 shows where).

Done when:

  • finance.py loads the CSV, skips the bad row with a line-numbered reason, and prints the summary above.
  • All money values are Decimal; report.json round-trips them as exact strings.
  • by_category and by_month totals match hand computation.
  • The script is safe to re-run (idempotent — it only reads the CSV and rewrites report.json atomically).
  • Type hints on load_transactions/summarise; uvx ruff check finance.py is clean.

Stretch ideas: Add a --month YYYY-MM filter and a per-month breakdown table. Add CSV output of the enriched transactions (a kind/category normalised export) via DictWriter (01A.9 §4.1). Add a budget check: warn when a category exceeds a BUDGETS dict constant (01A.10 §6.5 — magic numbers as named constants). Add recurring-expense detection: same description+amount in ≥2 months.

Common problems:

  • Decimal('not-a-number') raises decimal.InvalidOperation, not ValueError — catch both or the row kills the run (01A.2 §1.6).
  • Totals are floats — you called float() or sum() on strings; parse with Decimal and sum Decimals.
  • TypeError: unsupported operand in defaultdict(Decimal) — you initialised with int/float; defaultdict(Decimal) gives Decimal('0').
  • json.dumps fails on Decimal — use default=str or convert explicitly; never silently round to float.
  • CSV parses but amounts are off by a cent — check for a thousands separator (1,090.00 splits into two fields); strip commas before Decimal if your export has them.

Stretch

Stretch: Mini key-value database#

Goal: A persistent key-value store backed by a single JSON file — typed API, atomic writes, a CLI, doctest-tested, safe to re-run — the production-shaped version of 01A.9 §7.6.

What you'll practise:

Setup: Python 3.11+ as before. Create kvdb/ as a package folder inside a project folder kvproj/:

text
kvproj/
├── kvdb/
│   ├── __init__.py
│   ├── __main__.py       # one line: calls cli.main(), so `python3 -m kvdb` works
│   ├── store.py
│   └── cli.py
└── tests/            # doctest lives in store.py; this folder is for assert tests

Steps:

  1. Read the lesson's version first. Study 01A.9 §7.6 end to end — its save() uses tempfile.mkstemp + os.replace; yours should too.
  2. store.py — the typed core. A KeyValueStore class over a Path: get(key), set(key, value), delete(key), keys(), __len__, __contains__. Values must be JSON-serialisable — validate on set by round-tripping through json.dumps/loads and raise a custom StoreError (with a ValueError-style message naming the offending key) on failure. Load lazily on first access, keep the dict in memory, and save() atomically on every mutation (01A.9 §2.5). Define the on-disk shape as a TypedDict ({"version": int, "data": dict[str, Any]}) and document the version field for future migrations (01A.10 §3.1).
  3. Errors as a hierarchy. StoreError(Exception) base; KeyNotFoundError(StoreError) for missing keys on get/delete; SerializationError(StoreError) for un-storable values — the 01A.8 §3.6 pattern, so callers can except StoreError once.
  4. Doctests that run. Put >>> examples in store.py's docstrings (set/get/delete round-trip, the error cases) and run python3 -m doctest kvdb/store.py -v — real tests with zero framework (01A.3 §6.4).
  5. cli.py — the front end. Subcommands get KEY, set KEY VALUE (JSON-decode the value so set n 42 stores a number, set s '"hi"' stores a string — document this), delete KEY, list, stats — all operating on --db PATH (default store.json), with logging warnings for missing keys instead of tracebacks, exit code 1 when a key is not found and exit code 2 on usage errors (argparse already does that) (01A.8 §3.8).
  6. Assert tests. tests/test_store.py (end it with an if __name__ == "__main__": block that calls each test function, and run it from kvproj/ as python3 -m tests.test_store: running python3 tests/test_store.py puts tests/ on sys.path instead of kvproj/, so import kvdb fails): persistence across instances (write with one KeyValueStore, read with a fresh one), atomicity (kill mid-write simulation: write to the .tmp path is never visible as store.json), and the error hierarchy catches correctly.
  7. Verify and harden. Run the whole suite, then uvx ruff check kvdb/ and uvx mypy kvdb/. Add one production concern of your choice: a --dry-run on set/delete, file locking awareness (01A.9 §6.4), or a size guard that refuses values over N bytes.

Verify it, and what you should see:

bash
cd kvproj
python3 -m doctest kvdb/store.py
python3 -m kvdb --db demo.json set greeting '"hello"'
python3 -m kvdb --db demo.json set count 42
python3 -m kvdb --db demo.json get greeting
python3 -m kvdb --db demo.json list
python3 -m kvdb --db demo.json delete greeting
python3 -m kvdb --db demo.json get greeting   # key is gone: warning logged, exit code 1
cat demo.json
Example output · illustrative5 lines
hello
count    42
greeting "hello"
WARNING kvdb.cli: key 'greeting' not found
{"version": 1, "data": {"count": 42}}

The file demo.json must always be complete valid JSON — check it after every command, including after a kill -9 mid-set (the .tmp file may remain; store.json must not be truncated). python3 -m doctest prints nothing on success; add -v to see each example run.

Done when:

  • All doctests pass and tests/test_store.py asserts pass.
  • set/get/delete/list/stats work from the CLI against a persistent file.
  • Unserialisable values and missing keys raise your custom exceptions, never bare KeyError/TypeError leaking to the CLI.
  • A simulated crash mid-write leaves store.json intact (verify by inspecting the directory for .tmp leftovers and re-running).
  • uvx ruff check and uvx mypy are clean on kvdb/.

Stretch ideas: Add TTL/expiry metadata per key. Add a dump/load pair that round-trips the whole store through JSONL (01A.9 §3.5). Swap the JSON file for sqlite3 (01A.7 §5.3) behind the same KeyValueStore interface — the 01A.6 §2.5 Protocol seam makes the swap a one-file change. Add value-size and total-store-size guards.

Common problems:

  • store.json ends up truncated or half-written — you wrote in place; use temp-file-plus-os.replace every time (01A.9 §2.5).
  • Numbers come back as strings or vice versa — JSON round-trip is lossless for str/int/float/bool/None/list/dict only; tuples become lists and int dict keys become strings (01A.9 §3.2).
  • get on a missing key raises KeyError — wrap it in your KeyNotFoundError at the boundary.
  • Two processes corrupt the store — single-writer assumption; document it, or add the locking note from 01A.9 §6.4.
  • Doctests fail only on your machine — they contain absolute paths or timestamps; keep examples deterministic (fixed keys, fixed values).

Stretch

Stretch: Log pipeline with generators#

Goal: A streaming log processor that handles files far larger than memory: generate a big deterministic log, stream it through parse → classify → batch → aggregate stages as generators, emit JSONL results, and log the pipeline's own operation through a rotating file handler.

What you'll practise:

Setup: Python 3.11+ as before. Create logpipe/ with make_logs.py, pipeline.py, logs/ (created by the generator) and out/.

Steps:

  1. Generate the data. Write make_logs.py that writes ~200,000 deterministic log lines to logs/app.log — cycle through templates like the lesson's (2026-11-04 10:00:03 ERROR worker-1 db timeout after 30s (host=db-1)), varying worker, host, id and timing with a seeded random.Random(42) so runs are reproducible (01A.2 §1.7). Include ~5% malformed lines. Time it — generation should take seconds, and at roughly 70 bytes a line the file lands around 10–15 MB: small enough to generate instantly, big enough that holding every parsed record at once (about 90 MB of Python dicts) is visibly wasteful. Raise the line count to 2 million if you want the gap to hurt.
  2. Stage 1 — read_lines(path). A generator yielding lines from path.open(encoding="utf-8") inside with — constant memory (01A.5 §3.1).
  3. Stage 2 — parse_line(line). Regex with named groups (date, time, level, worker, msg) returning a dict or None for malformed lines; count and report skips (01A.9 §7.2).
  4. Stage 3 — signature(msg). The normalisation recipe from the lesson: collapse host=, id=, user=, timings so repeats group into signatures.
  5. Stage 4 — batched(iterable, n). Consume parsed records in groups of e.g. 10,000 with itertools.batched — and write the 3.11 fallback (iter() + islice) in a comment, since the module targets 3.11+ (01A.5 §4.1).
  6. Stage 5 — aggregate. Per batch, update Counters for levels and error signatures; after each batch, emit one JSONL record {"batch": n, "lines": k, "errors_so_far": {...top5...}} to out/batches.jsonl — streaming output, not one giant report (01A.9 §3.5).
  7. Pipeline logging. Configure logging once: console at INFO, plus RotatingFileHandler("out/pipeline.log", maxBytes=100_000, backupCount=3) (01A.8 §7.4). Log batch progress with lazy args (log.info("batch %d: %d lines", n, k) — never f-strings in log calls, 01A.8 §7.3).
  8. Prove the memory claim. Wrap the run in tracemalloc (the 01A.5 §3.2 technique) and print peak memory; then write the "eager" version behind a --eager flag, which keeps every parsed record in one list (records = [r for r in map(parse_line, read_lines(path)) if r]) before aggregating, and compare peaks on the same file. Materialising only the raw lines (list(read_lines(...))) would hold plain strings, roughly 25 MB for this file, so it understates the gap.

Verify it, and what you should see:

bash
cd logpipe
python3 make_logs.py
ls -lh logs/app.log                          # roughly 10-15 MB for 200,000 lines
python3 pipeline.py
wc -l out/batches.jsonl                      # one line per batch
head -2 out/batches.jsonl
cat out/pipeline.log | head -5
python3 pipeline.py --eager                  # compare peak memory
Example output · illustrative7 lines
wrote 200000 lines (12 MB) to logs/app.log
lazy peak memory : 4.6 MB
lazy: 200000 lines, 9987 bad, 17419 errors in 17 signatures
wrote 20 batch records to out/batches.jsonl
INFO pipeline: batch 1: 10000 lines, 900 errors so far
...
eager peak memory : 91 MB

The lazy pipeline's peak should stay at a few MB regardless of file size (it is set by the batch size, not the file) — that's the whole point (01A.5 §3.2's ~100× demonstration). The top error signature should collapse the template's volatile fields into one count, exactly like the lesson's 3x db timeout example.

Done when:

  • make_logs.py produces a deterministic, seeded log file large enough that loading every parsed record at once is clearly heavier than streaming it.
  • pipeline.py streams it end-to-end: constant-ish memory, per-batch JSONL output, rotating pipeline log.
  • Malformed lines are counted and reported, never fatal.
  • --eager demonstrates the memory difference on the same input.
  • uvx ruff check logpipe/ is clean; type hints on all stage functions.

Stretch ideas: Add a --since/--until time-window filter stage. Add signature trending: errors per batch over time as a small ASCII sparkline. Add gzip input (gzip.open instead of open — one-line swap, 01A.7 §5.11). Emit the final summary as the triage package's report.json shape so the two projects' outputs compare.

Common problems:

  • Memory grows with file size — a stage is materialising a list; check every stage yields (yield/return generator), including inside signature().
  • itertools.batched ImportError on 3.11 — use the documented islice fallback (01A.5 §4.1).
  • Signatures don't group — your normalisation regexes don't cover every volatile field; log a few raw msg values to see what's varying.
  • StopIteration/RuntimeError deep in the pipeline — a next() leaked out of a generator; use next(it, default) or for loops (01A.5's exhaustion bugs).
  • Pipeline log fills disk — that's what RotatingFileHandler(maxBytes, backupCount) is for; check out/ after the run.
  • Generator "does nothing" when called — calling a generator function only builds the generator; iterate it (01A.5 §3.1).

Stretch (optional)

Stretch (optional): Port a program#

Goal: Take a program written in PHP, JavaScript or Java — the lesson's four-language example or one of your own — and rewrite it as idiomatic Python, then prove the two produce identical output on shared inputs. This is the exercise that converts "I know another language" into "I think in Python".

What you'll practise:

  • The idiom translation table — 40 snippets mapped across the four languages (01A.11 Part 8)
  • The same program in four languages, side by side (01A.11 Part 10)
  • The Python-surprises gallery — every behaviour that will bite a translator (01A.11 Part 9)
  • defaultdict/Counter, JSON I/O, sorting with key= — the collections the port leans on (01A.4)
  • Proving equivalence with assert-based checks (01A.8 Part 8)

Setup: Python 3.11+ as before. You need to read the source language; you do not need PHP, Node or a JDK installed — the lesson's translations are the spec, and only the Python side runs. Create port/ with src_original.<ext>, report.py, tickets.json (the lesson's eight-ticket fixture, copied from 01A.11 Part 10) and test_equiv.py.

Steps:

  1. Pick your program. Easiest: the lesson's task — read tickets.json, group by status, count priority within each group, print a summary. Harder and better: write a ~40-line program in your own language first (a CSV report, a JSON transformer, a small CLI), then port it.
  2. Write the idiomatic Python. Not a transliteration — the Python idiom: json.loads + pathlib, defaultdict(list) grouping, Counter for counts, f-string output, if __name__ == "__main__" (01A.11 Part 10 shows the target shape; write your own variant so you're not copying).
  3. Generate shared fixtures. Create 3–5 input files exercising edge cases the program must agree on: empty input, missing optional fields, unicode text, duplicate keys, boundary values. Save them as fixtures/*.json (or .csv).
  4. Prove equivalence. test_equiv.py: for each fixture, run report.py and the original program (if you have the runtime) and assert byte-identical stdout; if you don't have the runtime, encode the expected output by hand from the spec and assert against it. Where outputs can legitimately differ (dict ordering, float formatting), normalise before comparing and say why.
  5. Surprise audit. Walk 01A.11 Part 9 and check your port for each trap relevant to your program: mutable defaults, is vs ==, truthiness of empty containers, ///% sign, sort() returning None, string immutability, module-level code on import. Fix what you find and note it in a PORTING_NOTES.md.
  6. Extend in Python only. Add one feature to the Python version (top-N per group, JSON output mode, a filter flag) that has no counterpart in the original — and write in your notes why the original would need it too, using the idiom table.

Verify it, and what you should see:

bash
cd port
python3 report.py tickets.json
python3 test_equiv.py
Example output · illustrative11 lines
8 tickets
  closed: 2
    low: 1
    normal: 1
  in-progress: 2
    normal: 1
    high: 1
  open: 4
    low: 1
    normal: 1
    high: 2

test_equiv.py should print all equivalence checks passed — every fixture produced identical output (or identical-after-normalisation, with the normalisation documented). Your PORTING_NOTES.md should list at least three surprises you actually hit or checked, each with the lesson section that explains it.

Done when:

  • report.py (or your port) produces the expected summary on the lesson's fixture and all your edge-case fixtures.
  • test_equiv.py proves output equivalence on every fixture.
  • PORTING_NOTES.md documents the translation decisions and the surprises found.
  • The Python version is idiomatic — a reviewer from another language would call it Python, not a transliteration.

Stretch ideas: Port back: take your Python version and re-express it in your source language to check the mapping is truly bidirectional. Add a second program (string processing, file I/O) to the port suite. Time-box it: 30 minutes per program, then move on — the goal is reps, not perfection.

Common problems:

  • Assuming PHP/JS truthiness — "0", [], {} differ across languages; check 01A.11 §2.3 before porting conditions.
  • Transliterating instead of translating — array_map/filter/reduce become comprehensions; ?./?? become .get()/or/if x is None (Part 8 table).
  • Equivalence test too weak — comparing only exit codes; compare full stdout on multiple fixtures including empty and malformed input.
  • Float formatting differs (0.1+0.2) — normalise or use Decimal on both sides; money never goes through float (01A.2 §1.6).
  • Module-level code runs on import — your "library" functions execute at import time; guard with if __name__ == "__main__" (01A.11 §9.8).
Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close