13. Pythonic code — Mini-project
A data team inherited legacy_sales_report.py. Every morning it reads the raw sales export data/sales_raw.csv and prints a quality report: rows, duplicates, parsed prices, bad quantities and revenue per region. The report is correct, and the finance team relies on it. Nobody dares to change the script, because nobody can read it.
Your job: refactor it into sales_report.py. The new script must print exactly the same report, pass ruff check and ruff format --check with the module configuration, and be easy to change next month.
This is the legacy script and its output:
import os, csv, sys
f = open(os.path.join("data", "sales_raw.csv"))r = csv.reader(f)header = next(r)data = []for row in r: data.append(row)f.close()
# remove duplicate rowsuniq = []for i in range(len(data)): if data[i] in uniq: continue uniq.append(data[i])
ri = header.index("region")pi = header.index("unit_price")qi = header.index("quantity")vi = header.index("revenue")
rev = {}cnt = {}prices = []bad = []for row in uniq: reg = row[ri].strip().title() if reg == "" or reg == "N/A" or reg == "-": reg = "Unknown" if reg in rev: rev[reg] = rev[reg] + float(row[vi]) cnt[reg] = cnt[reg] + 1 else: rev[reg] = float(row[vi]) cnt[reg] = 1 p = row[pi] try: p = float(p.replace("$", "").replace(",", "")) prices.append(p) except: pass q = int(row[qi]) if q <= 0 or q > 50: bad.append(row[0])
print("Rows read: %d" % len(data))print("Duplicates removed: %d" % (len(data) - len(uniq)))print("Prices parsed: " + str(len(prices)) + " of " + str(len(uniq)))print("Mean unit price: %.2f" % (sum(prices) / len(prices)))print("Bad quantities: " + str(len(bad)) + " (" + ", ".join(bad[:3]) + ", ...)")print("Revenue by region:")for k in sorted(rev, key=lambda k: rev[k], reverse=True): print(" %-8s %10.2f (%d lines)" % (k, rev[k], cnt[k]))Rows read: 1200Duplicates removed: 36Prices parsed: 1155 of 1164Mean unit price: 137.84Bad quantities: 10 (O002118, O006161, O006875, ...)Revenue by region: East 55700.87 (294 lines) North 51335.46 (288 lines) South 46414.87 (303 lines) West 39776.73 (262 lines) Unknown 2434.57 (17 lines)The project uses every part of module 13: loop and dict idioms, comprehensions, unpacking, EAFP parsing, PEP 8 names and constants, pathlib and with, the ruff workflow, the gotchas and a characterization check.
Dataset
Section titled “Dataset”data/sales_raw.csv has 1,200 rows and the 13 columns of data/sales.csv. It contains these problems (see the data dictionary):
| Problem | Column | Count |
|---|---|---|
| Exact duplicate rows | all | 36 |
Region in the wrong case or with spaces (north, North) |
region |
259 |
Missing tokens "", N/A, - |
region |
17 |
| Missing tokens | unit_price |
10 |
Price as text with a dollar sign ($79.99, "$1,299.00") |
unit_price |
1,190 |
| Negative or absurd quantity (-3 … 1000) | quantity |
10 |
The quantity limit comes from data/config.json: thresholds.max_quantity is 50. The revenue column is always present and correct.
Requirements
Section titled “Requirements”Your sales_report.py must:
-
Print the same report as the legacy script, byte for byte. Prove it with a characterization check: run both scripts and compare their output.
-
Read the file with
pathlib,withandcsv.DictReader, and refer to columns by name. -
Remove duplicates in one pass with a set, keeping the first copy of each row in the original order.
-
Parse prices in EAFP style in a function
parse_price(text) -> float | Nonethat catches onlyValueError. -
Normalize regions in a function, with the missing tokens in a constant set.
-
Count and sum with
Counteranddefaultdict(ordict.get), not withif key in d: ... else: .... -
Use comprehensions or generator expressions where they build a collection or a total.
-
Follow PEP 8:
snake_casenames that say what they hold,UPPER_CASEconstants for the file path, the missing tokens and the quantity limit, imports at the top. -
Use type hints and a docstring for every function, and a
main()function behindif __name__ == "__main__":. -
Contain none of the five gotchas: no mutable defaults, no closures in loops, no
isfor values, no float==, no list changed while you loop over it. -
Pass
ruff checkandruff format --checkwith this configuration inpyproject.toml:pyproject.toml [tool.ruff]line-length = 88target-version = "py312"[tool.ruff.lint]select = ["E", "W", "F", "I", "B", "UP", "SIM", "PTH"]
Step plan
Section titled “Step plan”-
Record the output. Run the legacy script and save its report:
python legacy_sales_report.py > expected.txt. This file is your characterization test. Do not edit it. -
Lint the legacy script. Run
ruff check --output-format concise legacy_sales_report.py. Read each finding. Note which ones are bugs and which are style. -
Create the skeleton. Make
sales_report.pywith a module docstring, the imports, the constants (RAW_PATH,MISSING_TOKENS,MAX_QUANTITY) and an emptymain(). -
Read the rows. Write
read_rows(path) -> list[dict[str, str]]withwithandcsv.DictReader. -
Remove the duplicates. Write
drop_duplicates(rows). A dict is not hashable, so usetuple(row.values())as the key in aset. The legacy script usedif data[i] in uniq, which scans the whole list for every row. -
Write the small parsers.
normalize_region(text)andparse_price(text). Test each in the REPL with" North ","N/A","$1,299.00"and"-". -
Build the report. Write
build_report(rows) -> list[str]. Return the lines instead of printing them, so you can compare them in a test. Keep the exact formats of the legacy script:%-8sis:<8,%10.2fis:10.2f. -
Compare after every step. Run
python sales_report.py > actual.txtanddiff expected.txt actual.txt. No output fromdiffmeans the files are equal. -
Run ruff.
ruff check sales_report.py, thenruff format sales_report.py, then compare the output once more.
A skeleton to start from:
"""Quality report for data/sales_raw.csv: duplicates, prices, quantities, regions."""
import csvfrom collections import Counter, defaultdictfrom pathlib import Path
RAW_PATH = Path("data") / "sales_raw.csv"# TODO: MISSING_TOKENS and MAX_QUANTITY
def read_rows(path: Path) -> list[dict[str, str]]: ... # TODO
def drop_duplicates(rows: list[dict[str, str]]) -> list[dict[str, str]]: ... # TODO: one pass, a set of tuple(row.values())
def normalize_region(text: str) -> str: ... # TODO
def parse_price(text: str) -> float | None: ... # TODO: EAFP
def build_report(rows: list[dict[str, str]]) -> list[str]: ... # TODO: the same lines as the legacy script
def main() -> None: """Print the quality report of the raw sales file.""" print("\n".join(build_report(read_rows(RAW_PATH))))
if __name__ == "__main__": main()Rubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Identical output | 4 | diff of the two reports prints nothing |
| File handling | 2 | pathlib, with and csv.DictReader; columns by name |
| Duplicates | 2 | One pass with a set; first copy kept, order preserved |
| EAFP parsing | 2 | parse_price() catches only ValueError; the try holds one line |
| Idioms | 3 | Counter/defaultdict, comprehensions, unpacking, sorted(..., key=...); no index loops |
| PEP 8 and names | 2 | snake_case, named constants, imports at the top, no one-letter names except in short comprehensions |
| Structure | 2 | Small functions with type hints and docstrings; main() and the __main__ guard |
| No gotchas | 1 | None of the five gotchas |
| Ruff | 2 | ruff check and ruff format --check pass |
| Total | 20 | 16 or more: you are ready for module 14 |
Stretch goals
Section titled “Stretch goals”- Turn the characterization check into a test:
assert build_report(read_rows(RAW_PATH)) == Path("expected.txt").read_text().splitlines(). Module 14 runs it with pytest. - Add a line
Missing regions: 17to the report. This is a behavior change: updateexpected.txton purpose and explain the change in one sentence. - Report the bad quantity rows with their quantities, for example
O002118 (999), sorted by quantity. - Count the stray spaces in the
productcolumn (leading, trailing and double inner spaces) with three generator expressions. - Read
MAX_QUANTITYand the missing tokens fromdata/config.jsoninstead of constants. Usedict.get()with the current values as defaults, so the script still runs if a key is missing.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your names can differ; your output must not.
Reference solution
"""Quality report for data/sales_raw.csv: duplicates, prices, quantities, regions."""
import csvfrom collections import Counter, defaultdictfrom pathlib import Path
RAW_PATH = Path("data") / "sales_raw.csv"MISSING_TOKENS = {"", "N/A", "-"}MAX_QUANTITY = 50 # thresholds.max_quantity in data/config.json
Row = dict[str, str]
def read_rows(path: Path) -> list[Row]: """Read the CSV file into a list of dicts, one per line.""" with path.open(newline="", encoding="utf-8") as f: return list(csv.DictReader(f))
def drop_duplicates(rows: list[Row]) -> list[Row]: """Keep the first copy of each row, in the original order.""" seen: set[tuple[str, ...]] = set() unique = [] for row in rows: key = tuple(row.values()) if key not in seen: seen.add(key) unique.append(row) return unique
def normalize_region(text: str) -> str: """Return the region in title case, or "Unknown" for a missing token.""" region = text.strip().title() return "Unknown" if region in MISSING_TOKENS else region
def parse_price(text: str) -> float | None: """Turn "$1,299.00" into 1299.0. Return None when the text is not a price.""" try: return float(text.removeprefix("$").replace(",", "")) except ValueError: return None
def build_report(rows: list[Row]) -> list[str]: """Return the report as a list of lines.""" unique = drop_duplicates(rows) parsed = [parse_price(row["unit_price"]) for row in unique] prices = [price for price in parsed if price is not None] bad_ids = [ row["order_id"] for row in unique if not 1 <= int(row["quantity"]) <= MAX_QUANTITY ] revenue: defaultdict[str, float] = defaultdict(float) line_counts: Counter[str] = Counter() for row in unique: region = normalize_region(row["region"]) revenue[region] += float(row["revenue"]) line_counts[region] += 1
report = [ f"Rows read: {len(rows)}", f"Duplicates removed: {len(rows) - len(unique)}", f"Prices parsed: {len(prices)} of {len(unique)}", f"Mean unit price: {sum(prices) / len(prices):.2f}", f"Bad quantities: {len(bad_ids)} ({', '.join(bad_ids[:3])}, ...)", "Revenue by region:", ] for region, total in sorted(revenue.items(), key=lambda kv: kv[1], reverse=True): report.append(f" {region:<8} {total:10.2f} ({line_counts[region]} lines)") return report
def main() -> None: """Print the quality report of the raw sales file.""" print("\n".join(build_report(read_rows(RAW_PATH))))
if __name__ == "__main__": main()Rows read: 1200Duplicates removed: 36Prices parsed: 1155 of 1164Mean unit price: 137.84Bad quantities: 10 (O002118, O006161, O006875, ...)Revenue by region: East 55700.87 (294 lines) North 51335.46 (288 lines) South 46414.87 (303 lines) West 39776.73 (262 lines) Unknown 2434.57 (17 lines)Check the characterization: run both scripts and compare their output.
diff <(python legacy_sales_report.py) <(python sales_report.py) && echo "Same report"Same reportCheck the style:
ruff check sales_report.py && ruff format --check sales_report.pyAll checks passed!1 file already formattedHow it works:
- Constants.
RAW_PATH,MISSING_TOKENSandMAX_QUANTITYreplace the inline path, the three==tests and the magic number 50. The comment says where 50 comes from. - Reading.
csv.DictReadergives one dict per row, so the code saysrow["region"]instead ofrow[ri], and the fourheader.index()calls go away. - Duplicates.
seenis a set of row tuples. Membership in a set takes about the same time for any size (module 04), so the pass is linear. The legacyin uniqscanned a growing list for each of the 1,200 rows. - Parsing.
parse_price()keeps only the conversion intryand catches onlyValueError. The legacy bareexcept:would also have hidden a typo. - Counting.
defaultdict(float)sums the revenue andCountercounts the lines, with noif region in revbranches. The twoparsed/pricescomprehensions build the price list, and thebad_idscomprehension states the rulenot 1 <= quantity <= MAX_QUANTITYonce. - Format. The f-string specs
:<8and:10.2freproduce%-8sand%10.2fexactly. Thediffcheck proves it. - Structure.
build_report()returns lines, so a test can call it without capturing printed output.main()and the__main__guard let another script importparse_price()without running the report.
Alternative: drop_duplicates() can be one line, list({tuple(row.values()): row for row in rows}.values()). A dict keeps the first insertion position of each key, so the order is right; but it keeps the last value for a key. That is correct here only because duplicates are exact copies. The explicit loop says “keep the first copy” without that subtlety.