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.
Dataset
Section titled “Dataset”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,quantityanddiscount. customer_id,regionandchannelmust not be a missing token.unit_pricemust be a positive number after removing$and,.quantitymust be a whole number from 1 to 50 (min_quantity,max_quantity).discountmust 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.
Requirements
Section titled “Requirements”Your script must:
- Define
DataValidationErrorwith the attributescolumnandline_number, and three subclasses:MissingColumnError,MissingValueErrorandInvalidValueError. - Check the header once, before any row, and raise
MissingColumnErrorthat names all missing columns. - Check every rule of every row and collect one exception object per broken rule. A row with two problems has two entries.
- Translate low-level errors (
ValueErrorfromint()orfloat()) intoInvalidValueErrorwithraise ... from. - Log to the terminal at
INFOwith the format%(levelname)s %(message)s, and tooutput/validation.logatDEBUGwith a timestamp:%(asctime)s %(levelname)-8s %(name)s %(message)s. Each problem is oneDEBUGline. The summary per error type and column is oneWARNINGline each. - 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).
- Take the file path as an optional command-line argument:
python validate_sales.py data/reports/2024-01.csv. Usesys.argv(module 08 introducesargparse). - Contain one
assertthat checks an invariant of your own code, not of the data. - Print the terminal report below for
data/sales_raw.csv, exactly.
INFO validating data/sales_raw.csvINFO 1200 rows read, 1101 valid, 99 rejectedWARNING InvalidValueError quantity 10WARNING MissingValueError channel 17WARNING MissingValueError customer_id 23WARNING MissingValueError discount 24WARNING MissingValueError region 17WARNING MissingValueError unit_price 10INFO details: output/validation.logStep plan
Section titled “Step plan”-
Exceptions. Write the base class with
__init__(self, message, *, column=None, line_number=None)and the three subclasses with docstrings. -
Logging setup. Write
setup_logging(): one named loggervalidateatDEBUG, aStreamHandleratINFOand aFileHandleratDEBUG, each with its ownFormatter. Create theoutput/folder first. -
Header check. Write
check_columns(header, source).csv.DictReader(f).fieldnamesgives the header. -
Cell checks. Write three small functions:
require()raisesMissingValueErrorfor a missing token;parse_number()converts withintorfloatand raisesInvalidValueErrorfrom theValueError;check_range()raisesInvalidValueErroroutside the limits. -
Row check. Write
row_problems(row, line_number). Call each check in its owntryblock and append the caught error to a list. Return the list. -
File check. Loop over the rows with
enumerate(reader, start=2)(line 1 is the header). Log each problem atDEBUGand count it by type and column. -
Main. Read the path from
sys.argv, call the file check, catchFileNotFoundErrorandMissingColumnError(logCRITICAL, return 1), log the summary and return 0. End the script withsys.exit(main(sys.argv))underif __name__ == "__main__":. -
Run it on the three test files. Then open
output/validation.logand find line 221 (theN/Aprice).
A skeleton to start from:
"""validate_sales.py: check a raw sales file before the cleaning step."""
import csvimport loggingimport sysfrom 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))Rubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- Write the valid rows to
output/sales_valid.csvwithcsv.DictWriter(module 07), with the price as a number and the region in title case. - Add a rule for
order_date: it must match one of the three formats incleaning.date_formatsofdata/config.json. Module 09 showsdatetime.strptime(), which raisesValueErrorfor a text that does not match. - Read the limits from
data/config.jsoninstead of constants, and raise aConfigError(chained withfrom) when a key is missing. - Add a command-line flag
--verbosethat sets the terminal handler toDEBUG. - Stop with exit code 2 when more than 5% of the rows are bad (
max_missing_fractionin the config is 0.05). Isdata/sales_raw.csvabove or below that limit?
Reference solution
Section titled “Reference solution”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: 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 csvimport loggingimport sysfrom pathlib import Path
log = logging.getLogger("validate")
LOG_FILE = Path("output/validation.log")MISSING_TOKENS = {"", "N/A", "-"} # cleaning.na_values in data/config.jsonREQUIRED_COLUMNS = [ "order_id", "customer_id", "region", "channel", "unit_price", "quantity", "discount",]MIN_QUANTITY, MAX_QUANTITY = 1, 50 # thresholds in data/config.jsonMAX_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))INFO validating data/sales_raw.csvINFO 1200 rows read, 1101 valid, 99 rejectedWARNING InvalidValueError quantity 10WARNING MissingValueError channel 17WARNING MissingValueError customer_id 23WARNING MissingValueError discount 24WARNING MissingValueError region 17WARNING MissingValueError unit_price 10INFO details: output/validation.logThe 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:
grep -c "" output/validation.logcut -d" " -f3- output/validation.log | head -4grep "line 221:" output/validation.log | cut -d" " -f3-110INFO validate validating data/sales_raw.csvDEBUG 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:
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: $?"INFO validating data/reports/2024-01.csvCRITICAL 2024-01.csv: missing columns ['customer_id', 'region', 'channel', 'unit_price', 'discount']exit code: 1INFO validating data/nope.csvCRITICAL cannot read data/nope.csv: No such file or directoryexit code: 1How it works:
- Exceptions.
DataValidationErrorstorescolumnandline_number. Its subclasses only add a name and a docstring.main()catchesMissingColumnErrorby type to stop the run;row_problems()catches the base class to collect any row problem. - Collecting instead of stopping. Each rule runs in its own
tryblock. A caught error goes into the list, and the next rule still runs. So a row that breaks two rules reports both. - Chaining.
parse_number()turnsValueErrorintoInvalidValueError ... from err. The log line says which line and column were wrong; a developer can still reach the original error in__cause__. - 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.
- 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. - 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. - Bugs stay visible. The last
except Exceptioninmain()logs the traceback withlog.exception()and re-raises, so a bug in the validator is never mistaken for bad data. - Assert.
assert bad_rows <= rowschecks 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.