Skip to content

06. Errors and debugging — Mini-project

A nightly pipeline cleans data/sales_raw.csv and trains a model on it. Last week the cleaning step crashed at 3 a.m. on a price of N/A, and nobody knew which rows were bad. Your team wants a validation step that runs before cleaning. It must never crash on bad data. It must say exactly what is wrong, keep the details in a log file and tell the scheduler, with an exit code, whether the file can be used at all.

Write a script, validate_sales.py, that does this. The project uses every part of module 06: custom exceptions, try/except/else/finally where they fit, raise and raise ... from, an assert for an invariant, and logging with two handlers.

data/sales_raw.csv has 1,200 rows and 13 columns. The rules come from data/config.json (thresholds and cleaning.na_values). The known problems, counted in the file:

Column Problem Rows
customer_id missing token ("", N/A, -) 23
region missing token 17
channel missing token 17
discount missing token 24
unit_price missing token 10
unit_price text with $ and a thousands separator, such as "$1,299.00" (not an error: parse it) 1,190
quantity negative (-3 to -1) 6
quantity absurd (250, 500, 999, 1000) 4

The rules:

  • The header must contain order_id, customer_id, region, channel, unit_price, quantity and discount.
  • customer_id, region and channel must not be a missing token.
  • unit_price must be a positive number after removing $ and ,.
  • quantity must be a whole number from 1 to 50 (min_quantity, max_quantity).
  • discount must be a number from 0 to 0.2 (max_discount).

To test the “unusable file” path, use data/reports/2024-01.csv: it has only 7 columns, so five required ones are missing. A path that does not exist, such as data/nope.csv, tests the missing-file path.

Your script must:

  1. Define DataValidationError with the attributes column and line_number, and three subclasses: MissingColumnError, MissingValueError and InvalidValueError.
  2. Check the header once, before any row, and raise MissingColumnError that names all missing columns.
  3. Check every rule of every row and collect one exception object per broken rule. A row with two problems has two entries.
  4. Translate low-level errors (ValueError from int() or float()) into InvalidValueError with raise ... from.
  5. Log to the terminal at INFO with the format %(levelname)s %(message)s, and to output/validation.log at DEBUG with a timestamp: %(asctime)s %(levelname)-8s %(name)s %(message)s. Each problem is one DEBUG line. The summary per error type and column is one WARNING line each.
  6. Return exit code 0 when the file was checked, and 1 when it cannot be used (missing file, missing columns). An unexpected bug must still show its traceback (log it, then re-raise).
  7. Take the file path as an optional command-line argument: python validate_sales.py data/reports/2024-01.csv. Use sys.argv (module 08 introduces argparse).
  8. Contain one assert that checks an invariant of your own code, not of the data.
  9. Print the terminal report below for data/sales_raw.csv, exactly.
Expected output
INFO validating data/sales_raw.csv
INFO 1200 rows read, 1101 valid, 99 rejected
WARNING InvalidValueError quantity 10
WARNING MissingValueError channel 17
WARNING MissingValueError customer_id 23
WARNING MissingValueError discount 24
WARNING MissingValueError region 17
WARNING MissingValueError unit_price 10
INFO details: output/validation.log
  1. Exceptions. Write the base class with __init__(self, message, *, column=None, line_number=None) and the three subclasses with docstrings.

  2. Logging setup. Write setup_logging(): one named logger validate at DEBUG, a StreamHandler at INFO and a FileHandler at DEBUG, each with its own Formatter. Create the output/ folder first.

  3. Header check. Write check_columns(header, source). csv.DictReader(f).fieldnames gives the header.

  4. Cell checks. Write three small functions: require() raises MissingValueError for a missing token; parse_number() converts with int or float and raises InvalidValueError from the ValueError; check_range() raises InvalidValueError outside the limits.

  5. Row check. Write row_problems(row, line_number). Call each check in its own try block and append the caught error to a list. Return the list.

  6. File check. Loop over the rows with enumerate(reader, start=2) (line 1 is the header). Log each problem at DEBUG and count it by type and column.

  7. Main. Read the path from sys.argv, call the file check, catch FileNotFoundError and MissingColumnError (log CRITICAL, return 1), log the summary and return 0. End the script with sys.exit(main(sys.argv)) under if __name__ == "__main__":.

  8. Run it on the three test files. Then open output/validation.log and find line 221 (the N/A price).

A skeleton to start from:

validate_sales.py (starter)
"""validate_sales.py: check a raw sales file before the cleaning step."""
import csv
import logging
import sys
from pathlib import Path
log = logging.getLogger("validate")
MISSING_TOKENS = {"", "N/A", "-"}
# TODO: DataValidationError and its three subclasses
def setup_logging():
# TODO: a terminal handler at INFO and a file handler at DEBUG
pass
def row_problems(row, line_number):
problems = []
# TODO: one try block per rule; append each caught DataValidationError
return problems
def main(argv):
setup_logging()
path = argv[1] if len(argv) > 1 else "data/sales_raw.csv"
# TODO: validate the file; return 1 if it cannot be used, else 0
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Criterion Points Full points when
Never crashes on bad data 3 All 1,200 rows are checked; no traceback for any bad cell
Correct counts 3 Every WARNING count equals the Dataset table
Exception hierarchy 2 One base class with column and line_number; three subclasses; caught by type, not by message text
Chaining 1 ValueError from a conversion is re-raised as InvalidValueError with from
Unusable files 2 Missing file and missing columns log CRITICAL and exit with code 1; the message lists all missing columns
Logging 3 Two handlers with the right levels and formats; one DEBUG line per problem in the file; no print() for status
Assert vs raise 1 raise for data rules; one assert for an invariant of the code
Readability 1 Small functions with docstrings; constants for the limits at the top
Total 16 13 or more: you are ready for module 07
  1. Write the valid rows to output/sales_valid.csv with csv.DictWriter (module 07), with the price as a number and the region in title case.
  2. Add a rule for order_date: it must match one of the three formats in cleaning.date_formats of data/config.json. Module 09 shows datetime.strptime(), which raises ValueError for a text that does not match.
  3. Read the limits from data/config.json instead of constants, and raise a ConfigError (chained with from) when a key is missing.
  4. Add a command-line flag --verbose that sets the terminal handler to DEBUG.
  5. Stop with exit code 2 when more than 5% of the rows are bad (max_missing_fraction in the config is 0.05). Is data/sales_raw.csv above or below that limit?

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

Reference solution
validate_sales.py
"""validate_sales.py: check a raw sales file before the cleaning step.
Usage: python validate_sales.py [path] (default: data/sales_raw.csv)
Exit code 0: the file was checked; bad rows are counted and logged.
Exit code 1: the file cannot be used (missing file or missing columns).
"""
import csv
import logging
import sys
from pathlib import Path
log = logging.getLogger("validate")
LOG_FILE = Path("output/validation.log")
MISSING_TOKENS = {"", "N/A", "-"} # cleaning.na_values in data/config.json
REQUIRED_COLUMNS = [
"order_id",
"customer_id",
"region",
"channel",
"unit_price",
"quantity",
"discount",
]
MIN_QUANTITY, MAX_QUANTITY = 1, 50 # thresholds in data/config.json
MAX_DISCOUNT = 0.2
# --- Exceptions ---------------------------------------------------------
class DataValidationError(Exception):
"""A value in the input data breaks a rule."""
def __init__(self, message, *, column=None, line_number=None):
super().__init__(message)
self.column = column
self.line_number = line_number
class MissingColumnError(DataValidationError):
"""A required column is not in the header."""
class MissingValueError(DataValidationError):
"""A required cell is empty or holds a missing-value token."""
class InvalidValueError(DataValidationError):
"""A cell has a value, but the value breaks a rule."""
# --- Logging ------------------------------------------------------------
def setup_logging():
"""Summary lines to the terminal; every detail, with a time, to a file."""
LOG_FILE.parent.mkdir(exist_ok=True)
log.setLevel(logging.DEBUG)
console = logging.StreamHandler() # stderr
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
to_file = logging.FileHandler(LOG_FILE, mode="w", encoding="utf-8")
to_file.setLevel(logging.DEBUG)
to_file.setFormatter(
logging.Formatter("%(asctime)s %(levelname)-8s %(name)s %(message)s")
)
log.addHandler(console)
log.addHandler(to_file)
# --- Checks -------------------------------------------------------------
def check_columns(header, source):
missing = [name for name in REQUIRED_COLUMNS if name not in (header or [])]
if missing:
raise MissingColumnError(
f"{Path(source).name}: missing columns {missing}", column=missing[0]
)
def require(row, column, line_number):
"""Return the stripped cell text, or raise MissingValueError."""
text = row[column].strip()
if text in MISSING_TOKENS:
raise MissingValueError(
f"line {line_number}: {column} is missing ({row[column]!r})",
column=column,
line_number=line_number,
)
return text
def parse_number(row, column, line_number, convert):
"""Convert a required cell with int or float; raise on bad text."""
text = require(row, column, line_number)
try:
return convert(text.removeprefix("$").replace(",", ""))
except ValueError as err:
raise InvalidValueError(
f"line {line_number}: {column} {text!r} is not a number",
column=column,
line_number=line_number,
) from err
def check_range(value, low, high, column, line_number):
if not low <= value <= high:
raise InvalidValueError(
f"line {line_number}: {column} {value} is outside {low}-{high}",
column=column,
line_number=line_number,
)
return value
def row_problems(row, line_number):
"""Return a list with one DataValidationError per broken rule."""
problems = []
for column in ("customer_id", "region", "channel"):
try:
require(row, column, line_number)
except DataValidationError as err:
problems.append(err)
try:
price = parse_number(row, "unit_price", line_number, float)
check_range(price, 0.01, float("inf"), "unit_price", line_number)
except DataValidationError as err:
problems.append(err)
try:
quantity = parse_number(row, "quantity", line_number, int)
check_range(quantity, MIN_QUANTITY, MAX_QUANTITY, "quantity", line_number)
except DataValidationError as err:
problems.append(err)
try:
discount = parse_number(row, "discount", line_number, float)
check_range(discount, 0.0, MAX_DISCOUNT, "discount", line_number)
except DataValidationError as err:
problems.append(err)
return problems
# --- Main ---------------------------------------------------------------
def validate(path):
"""Validate one file. Return (rows, bad_rows, problems by column)."""
with open(path, encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
check_columns(reader.fieldnames, path)
rows = bad_rows = 0
by_column = {}
for line_number, row in enumerate(reader, start=2):
rows += 1
problems = row_problems(row, line_number)
if problems:
bad_rows += 1
for err in problems:
log.debug("%s: %s", type(err).__name__, err)
key = f"{type(err).__name__} {err.column}"
by_column[key] = by_column.get(key, 0) + 1
assert bad_rows <= rows, "counted more bad rows than rows"
return rows, bad_rows, by_column
def main(argv):
setup_logging()
path = argv[1] if len(argv) > 1 else "data/sales_raw.csv"
log.info("validating %s", path)
try:
rows, bad_rows, by_column = validate(path)
except FileNotFoundError as err:
log.critical("cannot read %s: %s", path, err.strerror)
return 1
except MissingColumnError as err:
log.critical("%s", err)
return 1
except Exception:
log.exception("unexpected error while validating %s", path)
raise
log.info("%d rows read, %d valid, %d rejected", rows, rows - bad_rows, bad_rows)
for key in sorted(by_column):
log.warning("%-30s %3d", key, by_column[key])
log.info("details: %s", LOG_FILE)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Output
INFO validating data/sales_raw.csv
INFO 1200 rows read, 1101 valid, 99 rejected
WARNING InvalidValueError quantity 10
WARNING MissingValueError channel 17
WARNING MissingValueError customer_id 23
WARNING MissingValueError discount 24
WARNING MissingValueError region 17
WARNING MissingValueError unit_price 10
INFO details: output/validation.log

The terminal shows only the summary. The log file holds one line per problem, with a timestamp: 110 lines in all. grep -c "" counts the lines of a file. cut -d" " -f3- drops the first two space-separated fields (the date and the time), so the output on this page is the same on every run:

Terminal
grep -c "" output/validation.log
cut -d" " -f3- output/validation.log | head -4
grep "line 221:" output/validation.log | cut -d" " -f3-
Output
110
INFO validate validating data/sales_raw.csv
DEBUG validate MissingValueError: line 5: discount is missing ('')
DEBUG validate MissingValueError: line 15: channel is missing ('N/A')
DEBUG validate MissingValueError: line 16: region is missing ('N/A')
DEBUG validate MissingValueError: line 221: unit_price is missing ('N/A')

An unusable file stops the script with exit code 1. $? is the exit code of the last command:

Terminal
python validate_sales.py data/reports/2024-01.csv 2>&1; echo "exit code: $?"
python validate_sales.py data/nope.csv 2>&1; echo "exit code: $?"
Output
INFO validating data/reports/2024-01.csv
CRITICAL 2024-01.csv: missing columns ['customer_id', 'region', 'channel', 'unit_price', 'discount']
exit code: 1
INFO validating data/nope.csv
CRITICAL cannot read data/nope.csv: No such file or directory
exit code: 1

How it works:

  1. Exceptions. DataValidationError stores column and line_number. Its subclasses only add a name and a docstring. main() catches MissingColumnError by type to stop the run; row_problems() catches the base class to collect any row problem.
  2. Collecting instead of stopping. Each rule runs in its own try block. A caught error goes into the list, and the next rule still runs. So a row that breaks two rules reports both.
  3. Chaining. parse_number() turns ValueError into InvalidValueError ... from err. The log line says which line and column were wrong; a developer can still reach the original error in __cause__.
  4. Counts. 101 problems in 99 rows: two rows break two rules each. Every count equals the data dictionary, which is the strongest test you have.
  5. Logging. The terminal handler drops DEBUG, so the terminal shows the summary only. The file handler keeps every line with a timestamp for the morning after. print() is not used at all, so a scheduler can capture the log stream.
  6. Exit codes. sys.exit(main(sys.argv)) turns the return value into the exit code. A scheduler or a shell script (python validate_sales.py && python clean.py) can then decide whether to go on.
  7. Bugs stay visible. The last except Exception in main() logs the traceback with log.exception() and re-raises, so a bug in the validator is never mistaken for bad data.
  8. Assert. assert bad_rows <= rows checks the counting code, not the data. It can fail only if the loop is wrong.

Alternative: pandas (module 26) checks whole columns at once: df["customer_id"].isin(["", "N/A", "-"]).sum() counts the missing tokens of a column in one line. A row-by-row validator like this one is still useful for streaming input and for clear per-line messages; libraries such as pandera and pydantic (module 44) build on the same idea of typed validation errors.