Skip to content

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:

legacy_sales_report.py
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 rows
uniq = []
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]))
Output
Rows read: 1200
Duplicates removed: 36
Prices parsed: 1155 of 1164
Mean unit price: 137.84
Bad 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.

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.

Your sales_report.py must:

  1. Print the same report as the legacy script, byte for byte. Prove it with a characterization check: run both scripts and compare their output.

  2. Read the file with pathlib, with and csv.DictReader, and refer to columns by name.

  3. Remove duplicates in one pass with a set, keeping the first copy of each row in the original order.

  4. Parse prices in EAFP style in a function parse_price(text) -> float | None that catches only ValueError.

  5. Normalize regions in a function, with the missing tokens in a constant set.

  6. Count and sum with Counter and defaultdict (or dict.get), not with if key in d: ... else: ....

  7. Use comprehensions or generator expressions where they build a collection or a total.

  8. Follow PEP 8: snake_case names that say what they hold, UPPER_CASE constants for the file path, the missing tokens and the quantity limit, imports at the top.

  9. Use type hints and a docstring for every function, and a main() function behind if __name__ == "__main__":.

  10. Contain none of the five gotchas: no mutable defaults, no closures in loops, no is for values, no float ==, no list changed while you loop over it.

  11. Pass ruff check and ruff format --check with this configuration in pyproject.toml:

    pyproject.toml
    [tool.ruff]
    line-length = 88
    target-version = "py312"
    [tool.ruff.lint]
    select = ["E", "W", "F", "I", "B", "UP", "SIM", "PTH"]
  1. 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.

  2. 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.

  3. Create the skeleton. Make sales_report.py with a module docstring, the imports, the constants (RAW_PATH, MISSING_TOKENS, MAX_QUANTITY) and an empty main().

  4. Read the rows. Write read_rows(path) -> list[dict[str, str]] with with and csv.DictReader.

  5. Remove the duplicates. Write drop_duplicates(rows). A dict is not hashable, so use tuple(row.values()) as the key in a set. The legacy script used if data[i] in uniq, which scans the whole list for every row.

  6. Write the small parsers. normalize_region(text) and parse_price(text). Test each in the REPL with " North ", "N/A", "$1,299.00" and "-".

  7. 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: %-8s is :<8, %10.2f is :10.2f.

  8. Compare after every step. Run python sales_report.py > actual.txt and diff expected.txt actual.txt. No output from diff means the files are equal.

  9. Run ruff. ruff check sales_report.py, then ruff format sales_report.py, then compare the output once more.

A skeleton to start from:

sales_report.py (starter)
"""Quality report for data/sales_raw.csv: duplicates, prices, quantities, regions."""
import csv
from collections import Counter, defaultdict
from 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()
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
  1. 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.
  2. Add a line Missing regions: 17 to the report. This is a behavior change: update expected.txt on purpose and explain the change in one sentence.
  3. Report the bad quantity rows with their quantities, for example O002118 (999), sorted by quantity.
  4. Count the stray spaces in the product column (leading, trailing and double inner spaces) with three generator expressions.
  5. Read MAX_QUANTITY and the missing tokens from data/config.json instead of constants. Use dict.get() with the current values as defaults, so the script still runs if a key is missing.

Try the project yourself first. Then compare your script with this one. Your names can differ; your output must not.

Reference solution
sales_report.py
"""Quality report for data/sales_raw.csv: duplicates, prices, quantities, regions."""
import csv
from collections import Counter, defaultdict
from 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()
Output
Rows read: 1200
Duplicates removed: 36
Prices parsed: 1155 of 1164
Mean unit price: 137.84
Bad 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.

Terminal
diff <(python legacy_sales_report.py) <(python sales_report.py) && echo "Same report"
Output
Same report

Check the style:

Terminal
ruff check sales_report.py && ruff format --check sales_report.py
Output
All checks passed!
1 file already formatted

How it works:

  1. Constants. RAW_PATH, MISSING_TOKENS and MAX_QUANTITY replace the inline path, the three == tests and the magic number 50. The comment says where 50 comes from.
  2. Reading. csv.DictReader gives one dict per row, so the code says row["region"] instead of row[ri], and the four header.index() calls go away.
  3. Duplicates. seen is 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 legacy in uniq scanned a growing list for each of the 1,200 rows.
  4. Parsing. parse_price() keeps only the conversion in try and catches only ValueError. The legacy bare except: would also have hidden a typo.
  5. Counting. defaultdict(float) sums the revenue and Counter counts the lines, with no if region in rev branches. The two parsed/prices comprehensions build the price list, and the bad_ids comprehension states the rule not 1 <= quantity <= MAX_QUANTITY once.
  6. Format. The f-string specs :<8 and :10.2f reproduce %-8s and %10.2f exactly. The diff check proves it.
  7. Structure. build_report() returns lines, so a test can call it without capturing printed output. main() and the __main__ guard let another script import parse_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.