Module 01A: Projects
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:
uv python install 3.13 # or any Python 3.11+; see 01A.1 §2.1
uv run python --version # check what you're runningRun 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: 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:
- Dataclasses,
IntEnum/StrEnumvocabularies and the record shape every later module leans on (lesson 01A.6, Part 3, Part 4, thedataclassvsPydanticdecision table) - Rule-based classification: keyword scoring and priority suggestion (01A.3's triage functions; the appendix's
rules.py) - CSV and JSON loading with per-row error collection — one bad row never sinks a run (01A.9 §7.1, 01A.8 Part 9)
Countersummaries and sorting withkey=(01A.4 §4.8, §2.3)- Atomic report writes via temp-file-plus-
replace(01A.9 §2.5) - An
argparseCLI andpython -mpackage execution (01A.7 §5.9, Part 7) - Type hints on every public function, the style the rest of the path assumes (01A.10 Appendix A)
Setup: Python 3.11+ as above. Create a working folder triageproj/ — everything lives inside it:
triageproj/
├── data/
│ ├── tickets.csv
│ └── tickets.json
├── triage/
│ ├── __init__.py
│ ├── __main__.py
│ ├── models.py
│ ├── rules.py
│ ├── io.py
│ ├── report.py
│ └── cli.py
└── README.mdSteps:
-
Create the data files. Save
data/tickets.csvanddata/tickets.jsonexactly 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). -
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 earliertriage/version in 01A.7 instead, replace it with this final form — the vocabularies differ. -
Run it. From inside
triageproj/:bash python3 -m triageThe default input is
data/tickets.csvrelative to your current directory, not the package —cd triageprojfirst (the 01A.9 §1.1 trap). -
Run the JSON input.
python3 -m triage --input data/tickets.json --outdir reports-json— same pipeline, different loader, chosen by file extension. -
Read the warnings. The CSV run prints one
WARNING triage.io: skipping row 13and 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. -
Add
--dry-run. Following 01A.9 §6.3's habit, add a flag that prints the summary table but skipssave_report_json/save_report_csv. Prove it: run with and without the flag and diffreports/. -
Add JSONL input. Write
load_tickets_jsonl(path)inio.pyusing the streaming pattern from 01A.9 §3.5 (parse each line independently, collect per-line problems, never hold the whole file), wire it intoload_ticketsfor.jsonl, and create adata/tickets.jsonlby converting the JSON fixture one object per line. -
Prove it with asserts. Add
test_triage.pywith plainassertfunctions (the pre-pytest habit from 01A.8 Part 8):classify_ticketroutes "charged twice" to billing,summarisecounts match a hand-computed fixture, and loading the bad-row CSV returns 11 tickets plus 1 problem. Run it withpython3 test_triage.py— no framework needed. -
Optional polish. Run
uvx ruff check triage/anduvx ruff format --check triage/(01A.10 §6.4), thenuvx mypy triage/(01A.10 §5.2) and fix what they flag.
Verify it, and what you should see:
cd triageproj
python3 -m triage
python3 -m triage --input data/tickets.json --outdir reports-json
python3 test_triage.pyThe CSV run's real output (produced by the lesson's own listing — deterministic, your output should match exactly):
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.csvThe 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 triageruns fromtriageproj/and produces the table above plusreports/report.jsonandreports/report.csv.- The JSON input path works and its bad item is reported, not fatal.
--dry-runprints the same summary and writes no files..jsonlinput loads through the new streaming loader.test_triage.pypasses with plain asserts.- Your
README.mdexplains 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;cdintotriageproj/(01A.7 §3 coverssys.path).FileNotFoundErrorondata/tickets.csv— the default path is relative to your current directory; run fromtriageproj/or pass--input.- CSV rows parse but every
prioritylooks wrong — CSV gives strings; the appendix's_row_to_ticketupper-cases the value and then looks it up by member name (Priority["URGENT"]), sourgentworks but a number like1or a word likecriticalis reported asunknown 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
Prioritydirection — in the appendixURGENT = 1, lower means more urgent; 01A.6's earlier toolkit had it the other way. The appendix is canonical.
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, whylenisn't tokens (01A.2 Part 4, §4.7) Counterand sorting withkey=(01A.4 §4.8)- Packaging the functions into a
textkit/package with apython -m textkitCLI (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:
textkitproj/
├── textkit/
│ ├── __init__.py
│ ├── __main__.py
│ ├── words.py
│ ├── slug.py
│ ├── extract.py
│ ├── unicode_inspect.py
│ └── cli.py
└── sample.txtSteps:
-
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. -
words.py— word frequencies. Writeword_freq(text: str, top: int | None = None) -> list[tuple[str, int]]: lowercase, extract words withre.findall(r"[a-z0-9']+", text.lower()), count withCounter, returnmost_common(top). Keep punctuation out by not matching it — do not strip it afterwards. -
slug.py— the slugifier. Copyslugifyfrom 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). -
extract.py— field extraction. Write one compiled regex per field with named groups, andextract_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 IDsTKT-\d+, order IDsORD-\d+. Base the patterns on §5.5's practical patterns; usefinditerand handle zero matches gracefully (empty list, notNone). -
unicode_inspect.py— the Unicode inspector. Writeinspect_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 vialen(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. -
cli.py+__main__.py. AnargparseCLI with four subcommands —words FILE [--top N],slug TEXT,extract TEXT,unicode TEXT— dispatching to the modules, plus__init__.pyre-exporting the public functions and__main__.pycallingcli.main()sopython -m textkitworks (01A.7 §2.5). -
Verify and extend. Run every subcommand on
sample.txt, then add one feature: acleansubcommand that NFC-normalises, strips format characters and collapses whitespace — thenormalize_textrecipe from 01A.2 §7.3.
Verify it, and what you should see:
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é 🚀"$ 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/viapython -m textkit. slugproducescafe-deja-vu-2026-product-launch-noteson the sample title.extractfinds all four field kinds in the test string and returns empty lists (not errors) for absent kinds.unicodeshows the NFC/NFD difference foréand the byte/code-point counts for🚀.cleannormalises 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:
wordsshowscafinstead ofcafé— 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.wordscounts punctuation as words — your regex is matching non-word characters;[a-z0-9']+excludes them by construction.slugreturns mojibake or empty for non-Latin titles — expected; NFKD+ASCII only handles Latin scripts (01A.2 §6.2 says so).extractmisses the email — check your pattern againstomar+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 textkitfails withNo module named 'textkit'— run fromtextkitproj/, the folder containingtextkit/.
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:
csv.DictReader,newline="",encoding="utf-8", and per-row error collection (01A.9 §4.1, §7.3, 01A.8 Part 9)Decimalfor money — whyfloatis wrong for currency (01A.2 §1.6)defaultdict,Counter, grouping and sorting records (01A.4 §4.6, §4.8, §2.3)- JSON output and atomic writes (01A.9 §3.1, §2.5)
- Type hints and a clean module layout (01A.10)
Setup: Python 3.11+ as before. Create finance/ with finance.py and transactions.csv.
Steps:
-
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 -
load_transactions(path)infinance.py: open withnewline="", encoding="utf-8", iteratecsv.DictReaderwithenumerate(..., start=2), convertamountviaDecimal(row["amount"])(catchInvalidOperation/ValueErrorper row), validatekind in ("income", "expense")anddateshape, and return(transactions, problems)— a list of dataclassTransactionrecords plus"line N: reason"strings, exactly the 01A.8 Part 9 pattern. -
Aggregate.
summarise(transactions)returns a dict:count,income_total,expense_total,net,by_category(expense totals per category,Decimalthroughout),by_month(perYYYY-MMexpense totals), andtop_expense(the single largest). Usedefaultdict(Decimal)andCounter— but noteCountersums numbers, so forDecimaltotals preferdefaultdictaccumulation; useCounterfor counts (01A.4 §4.8). -
Report. Print a console table (category, total, count — sorted by total descending via
sorted(..., key=lambda kv: kv[1], reverse=True)), and writereport.jsonatomically (01A.9 §2.5) withjson.dumps(..., default=str)—Decimalisn't JSON-native, so serialise as strings to keep cents exact, and say so in a comment. -
Verify by hand. Before running, compute the expected totals yourself: income
5000.00, expenses551.54, net4448.46; groceries145.30, utilities260.45, transport97.30, entertainment28.50, health19.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:
cd finance
python3 finance.py transactions.csvLoaded 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.jsonreport.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.pyloads the CSV, skips the bad row with a line-numbered reason, and prints the summary above.- All money values are
Decimal;report.jsonround-trips them as exact strings. by_categoryandby_monthtotals match hand computation.- The script is safe to re-run (idempotent — it only reads the CSV and rewrites
report.jsonatomically). - Type hints on
load_transactions/summarise;uvx ruff check finance.pyis 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')raisesdecimal.InvalidOperation, notValueError— catch both or the row kills the run (01A.2 §1.6).- Totals are floats — you called
float()orsum()on strings; parse withDecimaland sumDecimals. TypeError: unsupported operandindefaultdict(Decimal)— you initialised withint/float;defaultdict(Decimal)givesDecimal('0').json.dumpsfails onDecimal— usedefault=stror convert explicitly; never silently round to float.- CSV parses but amounts are off by a cent — check for a thousands separator (
1,090.00splits into two fields); strip commas beforeDecimalif your export has them.
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:
- Atomic writes and why temp-file-plus-
replacematters (01A.9 §2.5, §7.6) - Custom exception hierarchies for domain errors (01A.8 §3.6)
pathlib, JSON round-trip limits (tuples→lists, int keys→strings) (01A.9 §3.2)- Type hints,
TypedDictfor the on-disk shape, anddataclass/Protocolchoices (01A.10 Parts 2–3) doctestand assert-based tests (01A.3 §6.4, 01A.8 Part 8)argparsesubcommands andloggingfor skips/errors (01A.7 §5.9, 01A.8 Part 7)
Setup: Python 3.11+ as before. Create kvdb/ as a package folder inside a project folder kvproj/:
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 testsSteps:
- Read the lesson's version first. Study 01A.9 §7.6 end to end — its
save()usestempfile.mkstemp+os.replace; yours should too. store.py— the typed core. AKeyValueStoreclass over aPath:get(key),set(key, value),delete(key),keys(),__len__,__contains__. Values must be JSON-serialisable — validate onsetby round-tripping throughjson.dumps/loadsand raise a customStoreError(with aValueError-style message naming the offending key) on failure. Load lazily on first access, keep the dict in memory, andsave()atomically on every mutation (01A.9 §2.5). Define the on-disk shape as aTypedDict({"version": int, "data": dict[str, Any]}) and document the version field for future migrations (01A.10 §3.1).- Errors as a hierarchy.
StoreError(Exception)base;KeyNotFoundError(StoreError)for missing keys onget/delete;SerializationError(StoreError)for un-storable values — the 01A.8 §3.6 pattern, so callers canexcept StoreErroronce. - Doctests that run. Put
>>>examples instore.py's docstrings (set/get/delete round-trip, the error cases) and runpython3 -m doctest kvdb/store.py -v— real tests with zero framework (01A.3 §6.4). cli.py— the front end. Subcommandsget KEY,set KEY VALUE(JSON-decode the value soset n 42stores a number,set s '"hi"'stores a string — document this),delete KEY,list,stats— all operating on--db PATH(defaultstore.json), withloggingwarnings for missing keys instead of tracebacks, exit code 1 when a key is not found and exit code 2 on usage errors (argparsealready does that) (01A.8 §3.8).- Assert tests.
tests/test_store.py(end it with anif __name__ == "__main__":block that calls each test function, and run it fromkvproj/aspython3 -m tests.test_store: runningpython3 tests/test_store.pyputstests/onsys.pathinstead ofkvproj/, soimport kvdbfails): persistence across instances (write with oneKeyValueStore, read with a fresh one), atomicity (kill mid-write simulation: write to the.tmppath is never visible asstore.json), and the error hierarchy catches correctly. - Verify and harden. Run the whole suite, then
uvx ruff check kvdb/anduvx mypy kvdb/. Add one production concern of your choice: a--dry-runonset/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:
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.jsonhello
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.pyasserts pass. set/get/delete/list/statswork from the CLI against a persistent file.- Unserialisable values and missing keys raise your custom exceptions, never bare
KeyError/TypeErrorleaking to the CLI. - A simulated crash mid-write leaves
store.jsonintact (verify by inspecting the directory for.tmpleftovers and re-running). uvx ruff checkanduvx mypyare clean onkvdb/.
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.jsonends up truncated or half-written — you wrote in place; use temp-file-plus-os.replaceevery 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). geton a missing key raisesKeyError— wrap it in yourKeyNotFoundErrorat 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: 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:
- Generators, laziness and real memory behaviour (01A.5 Part 3, §3.2, §3.4)
itertools.batched/isliceand the Python 3.11 fallback (01A.5 §4.1)- Regex log parsing and error signatures (01A.9 §7.2, 01A.2 §6.3)
Counteraggregation and JSONL streaming output (01A.4 §4.8, 01A.9 §3.5)loggingwithRotatingFileHandlerand lazy%sformatting (01A.8 §7.3–7.4, Part 7)- Context managers for the input file (01A.8 Part 4)
Setup: Python 3.11+ as before. Create logpipe/ with make_logs.py, pipeline.py, logs/ (created by the generator) and out/.
Steps:
- Generate the data. Write
make_logs.pythat writes ~200,000 deterministic log lines tologs/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 seededrandom.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. - Stage 1 —
read_lines(path). A generator yielding lines frompath.open(encoding="utf-8")insidewith— constant memory (01A.5 §3.1). - Stage 2 —
parse_line(line). Regex with named groups (date,time,level,worker,msg) returning a dict orNonefor malformed lines; count and report skips (01A.9 §7.2). - Stage 3 —
signature(msg). The normalisation recipe from the lesson: collapsehost=,id=,user=, timings so repeats group into signatures. - Stage 4 —
batched(iterable, n). Consume parsed records in groups of e.g. 10,000 withitertools.batched— and write the 3.11 fallback (iter()+islice) in a comment, since the module targets 3.11+ (01A.5 §4.1). - 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...}}toout/batches.jsonl— streaming output, not one giant report (01A.9 §3.5). - Pipeline logging. Configure
loggingonce: console at INFO, plusRotatingFileHandler("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). - 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--eagerflag, 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:
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 memorywrote 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 MBThe 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.pyproduces a deterministic, seeded log file large enough that loading every parsed record at once is clearly heavier than streaming it.pipeline.pystreams it end-to-end: constant-ish memory, per-batch JSONL output, rotating pipeline log.- Malformed lines are counted and reported, never fatal.
--eagerdemonstrates 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 insidesignature(). itertools.batchedImportError on 3.11 — use the documentedislicefallback (01A.5 §4.1).- Signatures don't group — your normalisation regexes don't cover every volatile field; log a few raw
msgvalues to see what's varying. StopIteration/RuntimeErrordeep in the pipeline — anext()leaked out of a generator; usenext(it, default)orforloops (01A.5's exhaustion bugs).- Pipeline log fills disk — that's what
RotatingFileHandler(maxBytes, backupCount)is for; checkout/after the run. - Generator "does nothing" when called — calling a generator function only builds the generator; iterate it (01A.5 §3.1).
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 withkey=— 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:
- Pick your program. Easiest: the lesson's task — read
tickets.json, group bystatus, countprioritywithin 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. - Write the idiomatic Python. Not a transliteration — the Python idiom:
json.loads+pathlib,defaultdict(list)grouping,Counterfor counts, f-string output,if __name__ == "__main__"(01A.11 Part 10 shows the target shape; write your own variant so you're not copying). - 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). - Prove equivalence.
test_equiv.py: for each fixture, runreport.pyand the original program (if you have the runtime) andassertbyte-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. - Surprise audit. Walk 01A.11 Part 9 and check your port for each trap relevant to your program: mutable defaults,
isvs==, truthiness of empty containers,///%sign,sort()returningNone, string immutability, module-level code on import. Fix what you find and note it in aPORTING_NOTES.md. - 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:
cd port
python3 report.py tickets.json
python3 test_equiv.py8 tickets
closed: 2
low: 1
normal: 1
in-progress: 2
normal: 1
high: 1
open: 4
low: 1
normal: 1
high: 2test_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.pyproves output equivalence on every fixture.PORTING_NOTES.mddocuments 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/reducebecome 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 useDecimalon both sides; money never goes throughfloat(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).