06. Errors and debugging
Real data is messy. A price arrives as "N/A", a region as " west ", a file is missing, a quantity is -3. Each of these stops a program with an error. This module teaches you to read the error, decide what to do about it, find the cause of a wrong result and leave a record of what your program did. The examples use the messy sales file data/sales_raw.csv, the sensor file data/readings.txt and the pipeline log data/logs/app.log.
What you will learn
Section titled “What you will learn”- Read a traceback with several frames from the bottom up, and find the line where the bad data entered.
- Know the common built-in exceptions and how they are grouped in a hierarchy.
- Handle errors with
try,except,elseandfinally, and catch only the exceptions you expect. - Raise exceptions with clear messages, re-raise them and chain them with
raise ... from. - Build a custom exception hierarchy for data validation, and choose between
assertandraise. - Find bugs with
breakpoint()and the pdb debugger, and record what a program does withlogging.
Prerequisites
Section titled “Prerequisites”- Functions, return values and lambdas: 05. Functions.
- Lists, dicts and comprehensions: 04. Data structures.
ifandforloops: 03. Control flow.- String methods such as
strip(),replace()andremoveprefix(): 02. Strings and text. - The error types
NameError,TypeError,ValueErrorandZeroDivisionError: 01. Python basics.
Concepts
Section titled “Concepts”Two kinds of errors
Section titled “Two kinds of errors”Python finds errors at two different times.
A syntax error is code that breaks the grammar of Python: a missing colon, a missing bracket, a wrong indent. Python reads the whole file before it runs any line, so a syntax error stops the program before the first line runs. Here python -c runs one line of code from the terminal:
python -c 'print("Total:", total' File "<string>", line 1 print("Total:", total ^SyntaxError: '(' was never closedThe caret (^) points at the bracket that was opened and never closed. The message says so in words. Note that Python did not complain about total, which is not defined. It never got that far: it found the syntax error before it ran anything.
An exception is an error that happens while the program runs. The code is valid Python, but one operation cannot work with the values it gets: float("N/A"), a dict lookup with a key that is not there, a division by zero. Python raises the exception: it stops the current line and looks for code that handles it. When no code handles it, the program stops and prints a traceback. Most of this module is about exceptions.
| Syntax error | Exception | |
|---|---|---|
| When | before the program runs | while the program runs |
| Cause | invalid code | valid code, unusable value or state |
| Example | print("Total:", total |
float("N/A") |
Can you handle it with try? |
no: fix the code | yes |
Reading a traceback
Section titled “Reading a traceback”A traceback is the report that Python prints when an exception stops a program. Module 01 showed tracebacks with one line of location. Real programs call functions that call other functions, so real tracebacks are longer.
This script totals the revenue of three lines from data/sales_raw.csv. The third line has the price N/A.
# clean_sales.py: total the revenue of three raw lines from data/sales_raw.csv.# The prices are text, as in the file: "$249.00", "$1,299.00" and "N/A".
rows = [ {"order_id": "O000004", "unit_price": "$249.00", "quantity": "1"}, {"order_id": "O000145", "unit_price": "$1,299.00", "quantity": "2"}, {"order_id": "O002982", "unit_price": "N/A", "quantity": "2"},]
def parse_price(text): """Turn price text such as "$1,299.00" into the float 1299.0.""" return float(text.removeprefix("$").replace(",", ""))
def line_revenue(row): price = parse_price(row["unit_price"]) return price * int(row["quantity"])
def total_revenue(rows): total = 0.0 for row in rows: total += line_revenue(row) return total
print("Total revenue:", total_revenue(rows))Run it with python clean_sales.py. Python prints this traceback:
Traceback (most recent call last): File "/path/to/my-course/clean_sales.py", line 28, in <module> print("Total revenue:", total_revenue(rows)) ~~~~~~~~~~~~~^^^^^^ File "/path/to/my-course/clean_sales.py", line 24, in total_revenue total += line_revenue(row) ~~~~~~~~~~~~^^^^^ File "/path/to/my-course/clean_sales.py", line 17, in line_revenue price = parse_price(row["unit_price"]) File "/path/to/my-course/clean_sales.py", line 13, in parse_price return float(text.removeprefix("$").replace(",", ""))ValueError: could not convert string to float: 'N/A'On your machine, Python prints your own project folder in place of /path/to/my-course, for example /Users/ana/course/clean_sales.py. This page shows /path/to/my-course in every path.
To understand the traceback, you need two words:
- The call stack (module 05) is the chain of function calls that are running at one moment. The script calls
total_revenue(), which callsline_revenue(), which callsparse_price(). - A frame is one entry of that chain: one function call, with its own local variables and the line it is running now.
The traceback lists one frame per call, oldest first. The header says so: most recent call last. Each frame has a location line (File "/path/to/my-course/clean_sales.py", line 24, in total_revenue) and the source line that was running. The carets (~~~^^^) mark the part of the line that was being evaluated. The last line names the exception and its message.
sequenceDiagram
participant S as script
participant T as total_revenue()
participant L as line_revenue()
participant P as parse_price()
S->>T: total_revenue(rows)
T->>L: line_revenue(row)
L->>P: parse_price("N/A")
P--xS: ValueError travels back up every frame
Read a traceback in this order:
-
The last line. What went wrong?
ValueError: could not convert string to float: 'N/A'. The message even shows the bad value. -
The last frame. Where did it happen? Line 13, in
parse_price. This is where Python gave up. In a traceback that ends inside a library (pandas, NumPy), walk up until you reach the first frame from your file. -
The frames above. How did the program get there? Line 17 passed
row["unit_price"], line 24 looped over the rows, line 28 started it all. Walk up until you find where the bad value came from. Here it came from the data: one row hasN/Aas its price.
The fix depends on what N/A means. If a missing price is allowed, skip the row and count it. If it is not allowed, stop with a clearer message. The rest of this module teaches both.
Built-in exceptions
Section titled “Built-in exceptions”Python has about 70 built-in exception types. A handful of them cover most of the errors you meet in data work:
| Exception | Raised when | Data example |
|---|---|---|
ValueError |
the type is right, but the value is not usable | float("N/A"), int("2.5") |
TypeError |
an operation gets a value of the wrong type | "Units: " + 3, len(42) |
KeyError |
a dict has no such key | targets["west"] when the key is "West" |
IndexError |
a list position is out of range | readings[40] in a list of 40 values |
AttributeError |
an object has no such attribute or method | None.strip() when a cell was empty |
NameError |
a name is not defined | a typo such as revenu |
ZeroDivisionError |
division by zero | revenue / order_count with 0 orders |
FileNotFoundError |
a file does not exist | open("data/sale.csv") |
UnicodeDecodeError |
bytes do not fit the encoding | a latin-1 file read as UTF-8 (module 07) |
ModuleNotFoundError |
an import cannot find the module | import sklearn outside your environment |
AssertionError |
an assert condition is false |
assert 0 <= discount <= 1 |
RecursionError |
recursion goes too deep | a recursive function with no base case |
NotImplementedError |
a method is a placeholder | a base class method that subclasses must write |
StopIteration |
an iterator has no more items | next(iter([])) (module 10) |
KeyboardInterrupt |
you press Ctrl+C | stopping a long training loop |
Run each failing operation and print the exception type and message. The block uses try and except, which the next section explains. For now, read except Exception as err as “if anything goes wrong, call the error err”.
store_regions = {"S01": "North", "S04": "South"}readings = [21.7, 22.1]
checks = [ ("float('N/A')", lambda: float("N/A")), ("'Units: ' + 3", lambda: "Units: " + 3), ("store_regions['S13']", lambda: store_regions["S13"]), ("readings[5]", lambda: readings[5]), ("None.strip()", lambda: None.strip()), ("2850 / 0", lambda: 2850 / 0), ("open('data/sale.csv')", lambda: open("data/sale.csv")), ("import sklearnx", lambda: __import__("sklearnx")),]for label, operation in checks: try: operation() except Exception as err: print(f"{label:<24} {type(err).__name__}: {err}")float('N/A') ValueError: could not convert string to float: 'N/A''Units: ' + 3 TypeError: can only concatenate str (not "int") to strstore_regions['S13'] KeyError: 'S13'readings[5] IndexError: list index out of rangeNone.strip() AttributeError: 'NoneType' object has no attribute 'strip'2850 / 0 ZeroDivisionError: division by zeroopen('data/sale.csv') FileNotFoundError: [Errno 2] No such file or directory: 'data/sale.csv'import sklearnx ModuleNotFoundError: No module named 'sklearnx'type(err).__name__ gives the name of the exception type. str(err), which the f-string uses for {err}, gives the message. Note that a KeyError message is only the missing key, in quotes.
Exceptions form a hierarchy, a family tree of types. A subclass is a more specific kind of its parent type, the base class. KeyError and IndexError are both kinds of LookupError. Every error that a program should handle is a kind of Exception. Above it sits BaseException, which also covers KeyboardInterrupt and SystemExit, the signals to stop a program.
flowchart TD
BE[BaseException] --> KI[KeyboardInterrupt]
BE --> SE[SystemExit]
BE --> E[Exception]
E --> AR[ArithmeticError] --> ZD[ZeroDivisionError]
E --> LE[LookupError]
LE --> KE[KeyError]
LE --> IE[IndexError]
E --> VE[ValueError] --> UE[UnicodeError] --> UDE[UnicodeDecodeError]
E --> TE[TypeError]
E --> OE[OSError] --> FNF[FileNotFoundError]
E --> IM[ImportError] --> MNF[ModuleNotFoundError]
E --> RE[RuntimeError] --> REC[RecursionError]
E --> OT["AttributeError, NameError,<br/>AssertionError, ..."]
The hierarchy matters because except LookupError catches a KeyError and an IndexError. issubclass() checks the family tree, and __mro__ lists every ancestor of a type:
>>> issubclass(KeyError, LookupError)True>>> issubclass(FileNotFoundError, OSError)True>>> issubclass(ValueError, TypeError)False>>> KeyError.__mro__(<class 'KeyError'>, <class 'LookupError'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>)try and except: handle an exception
Section titled “try and except: handle an exception”Exception handling means that your code catches an exception and decides what happens next, instead of letting the program stop. The try statement does it:
raw_values = ["21.7", "error", "", "22.4"] # lines from data/readings.txtreadings = []for raw in raw_values: try: readings.append(float(raw)) except ValueError: print(f"Skipped {raw!r}")print(readings)Skipped 'error'Skipped ''[21.7, 22.4]Python runs the try block. When a line in it raises an exception, Python skips the rest of the try block and checks each except clause in order. The first clause whose type matches the exception (the type or one of its base classes) runs. Then the program continues after the whole statement. When nothing matches, the exception travels up the call stack as if there were no try at all.
Four rules make except clauses safe and useful:
- Catch the exception you expect, and nothing else.
except ValueErrorhandles bad numbers. A typo in your code raises aNameError, which still stops the program and shows you the bug. - Put specific types before general ones. Python takes the first match, so
except Exceptionbeforeexcept ValueErrormakes the second clause dead code. - Use
as errwhen you need the details.erris the exception object. Its message isstr(err), its type istype(err). Python deleteserrat the end of theexceptblock. - Keep the
tryblock short. Put only the line that can fail inside it. Then you know which line raised the exception.
One statement can handle different exceptions in different ways. A tuple catches several types with one clause:
def parse_quantity(row): """Return the quantity as an int, or None if the row has no usable value.""" try: return int(row["quantity"]) except KeyError: print(" the row has no quantity column") except (ValueError, TypeError) as err: print(f" bad quantity {row['quantity']!r}: {type(err).__name__}") return None
for row in [{"quantity": "2"}, {"qty": "2"}, {"quantity": "2.5"}, {"quantity": None}]: print(row, "->", parse_quantity(row)){'quantity': '2'} -> 2 the row has no quantity column{'qty': '2'} -> None bad quantity '2.5': ValueError{'quantity': '2.5'} -> None bad quantity None: TypeError{'quantity': None} -> NoneThe print() inside the function runs before the print() of the loop line has finished, so each message appears above its result. The TypeError comes from int(None): a missing cell in a dict of records is often None.
A bare except (except: with no type) catches everything, including KeyboardInterrupt, so you cannot stop the program with Ctrl+C. except Exception: is only a little better: it hides your own bugs. In this function, a typo makes every result None, and nothing tells you why:
def revenue_share(revenue, target): try: return revenu / target # typo: revenu instead of revenue except Exception: return None
print(revenue_share(464.06, 550.0))NoneWith except ZeroDivisionError:, the typo would raise a NameError and the traceback would point at the line at once.
else and finally
Section titled “else and finally”A try statement has two more optional clauses:
elseruns only when thetryblock raised no exception. Put the code that should run after a success here, outside thetryblock, so that its own errors are not caught by mistake.finallyruns always: after a success, after a handled exception, after an unhandled one, and even after areturn. Use it for cleanup: close a connection, delete a temporary file, record that a step ended.
flowchart TD
T["try block"] -->|no exception| EL["else block"]
T -->|exception matches| EX["except block"]
T -->|no match| FU["finally block"]
EL --> F["finally block"]
EX --> F
F --> N["next statement"]
FU --> UP["exception travels up"]
def load_reading(raw): print(f"-- {raw!r}") try: value = float(raw) except ValueError: print("except: not a number") return None else: print("else: converted to", value) return value finally: print("finally: step done")
print("result:", load_reading("21.7"))print("result:", load_reading("n/a"))-- '21.7'else: converted to 21.7finally: step doneresult: 21.7-- 'n/a'except: not a numberfinally: step doneresult: NoneBoth calls print the finally line, even though both branches return first. Python runs finally on the way out of the function. Module 07 introduces with, which closes a file for you; it uses the same mechanism as finally.
| Clause | Runs when | Typical use |
|---|---|---|
try: |
always, first | the one operation that can fail |
except T: |
the try block raised a T |
recover: skip, default value, retry, report |
else: |
the try block raised nothing |
the next steps after a success |
finally: |
always, last | cleanup that must happen |
raise: signal a problem yourself
Section titled “raise: signal a problem yourself”Your own functions can raise exceptions too. Use raise when a function gets a value it cannot work with. The caller then decides what to do. A function that returns a wrong result quietly is worse: the error shows up much later, in a chart or a model, far from its cause.
def check_quantity(quantity, line_number): if quantity < 1: message = f"line {line_number}: quantity must be at least 1, got {quantity}" raise ValueError(message) return quantity
print(check_quantity(2, 2))print(check_quantity(-3, 579)) # line 579 of data/sales_raw.csv2ValueError: line 579: quantity must be at least 1, got -3A good message answers three questions: where (line 579), what (the quantity) and why (it must be at least 1, the value is -3). Choose the type that fits: ValueError for a bad value, TypeError for a wrong type, KeyError for a missing key.
A bare raise inside an except block re-raises the exception that is being handled. Use it when you want to add a report and still let the caller see the error:
def parse_or_report(raw, line_number): try: return float(raw) except ValueError: print(f"line {line_number}: cannot parse {raw!r}") raise
parse_or_report("n/a", 35)line 35: cannot parse 'n/a'ValueError: could not convert string to float: 'n/a'Exception chaining with raise … from
Section titled “Exception chaining with raise … from”A low-level error message such as could not convert string to float: 'N/A' does not say which file, line or column was wrong. Exception chaining links a new, clearer exception to the original one. Write raise NewError(...) from err inside the except block. The new exception keeps the old one in its __cause__ attribute, and the traceback shows both.
# price_chain.py: turn a low-level ValueError into a clear data error.
class DataValidationError(Exception): """A value in the input data breaks a rule."""
def parse_price(text, line_number): try: return float(text.removeprefix("$").replace(",", "")) except ValueError as err: message = f"line {line_number}: unit_price {text!r} is not a price" raise DataValidationError(message) from err
print(parse_price("$1,299.00", 12))print(parse_price("N/A", 221))1299.0Traceback (most recent call last): File "/path/to/my-course/price_chain.py", line 10, in parse_price return float(text.removeprefix("$").replace(",", ""))ValueError: could not convert string to float: 'N/A'
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "/path/to/my-course/price_chain.py", line 17, in <module> print(parse_price("N/A", 221)) ~~~~~~~~~~~^^^^^^^^^^^^ File "/path/to/my-course/price_chain.py", line 13, in parse_price raise DataValidationError(message) from errDataValidationError: line 221: unit_price 'N/A' is not a priceRead a chained traceback from the bottom too. The last block is the error your code raised, with a message for people. The block above it is the cause, with the low-level details. The line class DataValidationError(Exception): creates a new exception type; the next section explains it.
| You write | Traceback shows | Use when |
|---|---|---|
raise New(...) from err |
both, joined by “The above exception was the direct cause of the following exception” | you translate an error into a clearer one |
raise New(...) inside except |
both, joined by “During handling of the above exception, another exception occurred” | (usually an accident: a bug in the handler) |
raise New(...) from None |
only the new one | the old error adds nothing for the reader |
Custom exceptions for data validation
Section titled “Custom exceptions for data validation”A custom exception is an exception type that you define. It names a problem of your own domain, such as “a required column is missing”. The caller can then catch exactly that problem.
You define one with a class statement. Module 18 teaches classes in full. For exceptions you need only one pattern: class Name(Base): makes Name a new subclass of Base. The docstring documents it. Build a small hierarchy with one base class for the whole family:
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."""__init__ runs when you create the exception. super().__init__(message) passes the message to Exception, so str(err) and the traceback show it. The two extra attributes (values stored on the object, read with a dot) keep the column and the line number, so a handler can count problems by column. The three subclasses inherit __init__, so they need only their docstring.
flowchart TD
EX[Exception] --> DV[DataValidationError]
DV --> MC[MissingColumnError]
DV --> MV[MissingValueError]
DV --> IV[InvalidValueError]
try: raise MissingValueError( "line 221: unit_price is missing", column="unit_price", line_number=221 )except DataValidationError as err: print(type(err).__name__, "|", err, "|", err.column, err.line_number)print(issubclass(MissingValueError, DataValidationError))print(issubclass(MissingValueError, ValueError))MissingValueError | line 221: unit_price is missing | unit_price 221TrueFalseThe handler catches the base class, so it catches all three subclasses. A caller that cares about one problem can catch only that subclass. Name every exception type with the suffix Error, as the built-in types do. Example 4 uses this hierarchy on the full sales file.
assert or raise?
Section titled “assert or raise?”An assert statement checks a condition and raises AssertionError when it is false: assert total >= 0, "total is negative". It looks like a short form of if ...: raise, but it has a different job.
Python removes every assert when it runs with the optimize flag -O (python -O script.py). So an assert must never be the only guard against bad data. Example 5 shows a wrong price that slips through this way.
assert condition, message |
if not condition: raise SomeError(message) |
|
|---|---|---|
| Checks | an invariant: a fact that is always true if your code is correct | input that can be wrong: data, files, user input, arguments |
| A failure means | a bug in the program | bad input, which the caller can handle |
Removed by python -O |
yes | no |
| Error type | always AssertionError |
the type that fits: ValueError, MissingColumnError |
| Typical place | tests, self-checks at the end of a step | the start of a public function, a validation step |
Debugging: from print to pdb
Section titled “Debugging: from print to pdb”Debugging is finding and fixing the cause of a wrong result or a crash. A crash gives you a traceback. A wrong result gives you nothing, which is harder. Work in steps:
-
Reproduce the problem with the smallest input that shows it: three rows, not 20,000.
-
Read the traceback, if there is one, from the bottom up.
-
Inspect the values. A quick
print(f"{total=}")shows a name and its value. The f-string spec=printstotal=224.1. -
Pause the program and look around with a debugger, when prints are not enough.
-
Fix the cause, then add an
assertor a test (module 14) so the bug cannot come back.
A debugger is a tool that pauses a running program, so you can inspect variables and run it one line at a time. Python ships with one, pdb (the Python debugger). The built-in function breakpoint() opens pdb at that line. A breakpoint is a place where the program pauses. At the (Pdb) prompt, you type commands:
| Command | Does |
|---|---|
p expr |
print the value of an expression: p total, p row["unit_price"] |
pp expr |
pretty-print a long value, such as a dict of records |
n (next) |
run the current line, stop at the next line in this function |
s (step) |
run the current line, and stop inside a function it calls |
c (continue) |
run until the next breakpoint or the end |
l / ll |
list the source around the current line / the whole function |
w (where) |
print the call stack, like a traceback |
u / d |
move up to the caller’s frame / back down |
b 12 |
set a breakpoint at line 12 |
q (quit) |
stop the program |
h |
help |
Three more ways to start pdb:
python -m pdb clean_sales.py # start inside pdb, paused before the first statementpython -m pdb -c continue clean_sales.py # run; on a crash, pause at the failing framePYTHONBREAKPOINT=0 python debug_total.py # ignore every breakpoint() callThe third line sets an environment variable, a named setting that the shell passes to the program. The second line is post-mortem debugging: you inspect the variables of the frame that crashed, after the crash. Editors such as VS Code have a graphical debugger with the same ideas: breakpoints, step over (n), step into (s), continue (c) and a variables panel. Example 6 runs a real pdb session.
Logging: a record of what the program did
Section titled “Logging: a record of what the program did”print() is fine for a quick look. A program that runs every night needs more: messages with a time and a severity, that go to a file, that you can switch to more detail without editing the code. The logging module of the standard library does this.
Logging means writing messages about what a program does, while it runs. Three objects do the work:
- A logger is the object you send messages to. Get one by name:
logging.getLogger("sales.cleaner"). Names with dots form a tree:sales.cleaneris a child ofsales. - A handler sends the messages somewhere:
StreamHandlerto the terminal (stderr by default),FileHandlerto a file. - A formatter (log formatter) decides how one message line looks.
flowchart LR
C["log.warning(...)"] --> L["Logger<br/>sales.cleaner"]
L --> H1["StreamHandler<br/>terminal, WARNING+"]
L --> H2["FileHandler<br/>validation.log, DEBUG+"]
H1 --> F1["Formatter"]
H2 --> F2["Formatter"]
Each message has a log level, a number that says how serious it is. A logger and a handler each have a level too. They drop every message below it.
| Level | Number | Use for | Data pipeline example |
|---|---|---|---|
DEBUG |
10 | detail for the developer | Parsed row 221: {...} |
INFO |
20 | normal progress | Loaded 1200 rows from sales_raw.csv |
WARNING |
30 | something odd; the program continues | 23 rows with missing customer_id |
ERROR |
40 | a step failed | Failed to parse data/reports/2024-04.csv |
CRITICAL |
50 | the program cannot continue | Database unreachable, aborting |
The default level is WARNING, so DEBUG and INFO messages are hidden until you lower it. logging.basicConfig() sets up the root logger, the top of the tree, with one handler. Log messages go to stderr, the error stream of the terminal, so they do not mix with the data a script prints to stdout. (This page shows stderr in the Output block.)
import logging
logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(name)s] %(message)s", force=True,)log = logging.getLogger("sales.cleaner")
log.debug("raw header: %s", ["order_id", "order_date", "unit_price"])log.info("loaded %d rows from %s", 1200, "data/sales_raw.csv")log.warning("%d rows with missing customer_id", 23)INFO [sales.cleaner] loaded 1200 rows from data/sales_raw.csvWARNING [sales.cleaner] 23 rows with missing customer_idThe DEBUG line is missing because the level is INFO. force=True replaces any earlier setup, so you can run the block twice. Pass values as extra arguments with %s (any value), %d (whole number) or %r (repr) placeholders, not as an f-string: logging builds the text only when the message is really shown.
The format string uses LogRecord attributes, the fields of one message:
| Attribute | Shows | Example |
|---|---|---|
%(asctime)s |
date and time | 2024-05-01 10:53:56,110 |
%(levelname)s |
level name | WARNING |
%(levelname)-8s |
level name, padded to 8 characters | INFO |
%(name)s |
logger name | sales.cleaner |
%(message)s |
the message with its arguments | 23 rows with missing customer_id |
%(funcName)s, %(lineno)d |
function and line of the call | load_report, 58 |
%(module)s, %(filename)s |
module and file of the call | loader, loader.py |
The course log data/logs/app.log uses the format "%(asctime)s %(levelname)s [%(name)s] %(message)s". Runnable examples on this page leave out %(asctime)s, because the time changes on every run.
Worked examples
Section titled “Worked examples”Example 1 — Find the cause of a KeyError in a traceback
Section titled “Example 1 — Find the cause of a KeyError in a traceback”Goal: A report script compares the revenue of each region with its monthly target. It crashes on three lines from data/sales_raw.csv. Read the traceback, find where the bad value entered and fix the cause.
Step 1 — Run the script
Section titled “Step 1 — Run the script”# region_report.py: revenue of each region as a share of its target.# The rows are lines from data/sales_raw.csv, where the region text is messy.
targets = {"North": 600.0, "South": 500.0, "East": 650.0, "West": 550.0}
rows = [ {"order_id": "O000004", "region": "West", "revenue": 224.1}, {"order_id": "O000005", "region": "East", "revenue": 29.99}, {"order_id": "O000051", "region": "west", "revenue": 239.96},]
def revenue_by_region(rows): totals = {} for row in rows: region = row["region"] totals[region] = totals.get(region, 0.0) + row["revenue"] return totals
def share_of_target(totals): return {region: total / targets[region] for region, total in totals.items()}
def main(): totals = revenue_by_region(rows) for region, share in share_of_target(totals).items(): print(f"{region}: {share:.1%} of target")
if __name__ == "__main__": # run main() only when started as a script main()Traceback (most recent call last): File "/path/to/my-course/region_report.py", line 32, in <module> main() ~~~~^^ File "/path/to/my-course/region_report.py", line 27, in main for region, share in share_of_target(totals).items(): ~~~~~~~~~~~~~~~^^^^^^^^ File "/path/to/my-course/region_report.py", line 22, in share_of_target return {region: total / targets[region] for region, total in totals.items()} ~~~~~~~^^^^^^^^KeyError: 'west'The script printed no line of the report. The exception happened while share_of_target() built its dict, before the loop in main() could print.
Step 2 — Read the last line and the last frame
Section titled “Step 2 — Read the last line and the last frame”python -c "from region_report import targets; print('west' in targets, sorted(targets))"False ['East', 'North', 'South', 'West']A KeyError message is the missing key, and the last frame (line 22, carets under targets[region]) shows the lookup. targets has 'West' but no 'west'. The script runs main() only under if __name__ == "__main__":, so you can import from it without starting the report (module 08).
Step 3 — Walk up to find where the value came from
Section titled “Step 3 — Walk up to find where the value came from”The traceback shows where the error surfaced, not where the bad value entered. The keys of totals come from revenue_by_region(), which had already returned, so it is not in the traceback. Inspect its result:
python -c "from region_report import revenue_by_region, rows; print(revenue_by_region(rows))"{'West': 224.1, 'East': 29.99, 'west': 239.96}There are two keys for one region: 'West' and 'west'. The raw file has 259 region values in the wrong case or with spaces (north, NORTH, North). revenue_by_region() copied them as they were.
Step 4 — Fix the cause, not the symptom
Section titled “Step 4 — Fix the cause, not the symptom”Clean the region where it enters the program:
# region_report.py: revenue of each region as a share of its target.# The rows are lines from data/sales_raw.csv, where the region text is messy.
targets = {"North": 600.0, "South": 500.0, "East": 650.0, "West": 550.0}
rows = [ {"order_id": "O000004", "region": "West", "revenue": 224.1}, {"order_id": "O000005", "region": "East", "revenue": 29.99}, {"order_id": "O000051", "region": "west", "revenue": 239.96},]
def revenue_by_region(rows): totals = {} for row in rows: region = row["region"].strip().title() # " west " -> "West" totals[region] = totals.get(region, 0.0) + row["revenue"] return totals
def share_of_target(totals): return {region: total / targets[region] for region, total in totals.items()}
def main(): totals = revenue_by_region(rows) for region, share in share_of_target(totals).items(): print(f"{region}: {share:.1%} of target")
if __name__ == "__main__": # run main() only when started as a script main()python region_report_fixed.pyWest: 84.4% of targetEast: 4.6% of targetNow both West lines add up: 224.10 + 239.96 = 464.06, which is 84.4% of 550. A try/except KeyError in share_of_target() would also stop the crash, but it would drop the 'west' revenue from the report. That hides the symptom and keeps the wrong number.
Common mistakes:
- Fixing the line in the last frame by reflex. The last frame is where Python gave up, not always where the bug is.
- Reading the traceback from the top. The top frame is the start of the program, the least useful place.
- Silencing the error with
except KeyError: pass. The report then runs and is wrong.
Example 2 — Skip the bad lines of a readings file
Section titled “Example 2 — Skip the bad lines of a readings file”Goal: data/readings.txt has one temperature per line, but 3 of its 43 lines are broken. Compute the mean of the valid readings and report each bad line with its line number.
Step 1 — Read the lines
Section titled “Step 1 — Read the lines”with open("data/readings.txt", encoding="utf-8") as f: lines = f.read().splitlines()print(len(lines), "lines")print(lines[9:13])43 lines['22.9', '22.7', 'error', '22.4']open() opens the file, with closes it again, read() returns the whole text and splitlines() cuts it into a list of lines. Module 07 explains each part. Line 12 (index 11) holds error.
Step 2 — Convert each line and catch the failures
Section titled “Step 2 — Convert each line and catch the failures”readings = []bad_lines = []for line_number, raw in enumerate(lines, start=1): try: value = float(raw) except ValueError: bad_lines.append((line_number, raw)) else: readings.append(value)print(len(readings), "valid readings")print("bad lines:", bad_lines)40 valid readingsbad lines: [(12, 'error'), (24, ''), (35, 'n/a')]enumerate(lines, start=1) numbers the lines as an editor does. Only float(raw) sits in the try block. The append that should run after a success is in else, so a bug in it would not be mistaken for a bad line. The empty line 24 raises a ValueError too: float("") cannot read an empty string.
Step 3 — Report the result
Section titled “Step 3 — Report the result”mean = sum(readings) / len(readings)print(f"Mean of {len(readings)} readings: {mean:.2f} °C")for line_number, raw in bad_lines: print(f" line {line_number}: skipped {raw!r}")Mean of 40 readings: 21.06 °C line 12: skipped 'error' line 24: skipped '' line 35: skipped 'n/a'The report tells the reader what was left out. A mean that silently drops lines is hard to trust.
Step 4 — Handle a missing file
Section titled “Step 4 — Handle a missing file”path = "data/reading.txt" # a typo in the file nametry: with open(path, encoding="utf-8") as f: lines = f.read().splitlines()except FileNotFoundError as err: print(f"Cannot read {err.filename!r}: {err.strerror}")Cannot read 'data/reading.txt': No such file or directoryFileNotFoundError is a subclass of OSError. Its object has the attributes filename and strerror, which make a clear message. Here a script should usually stop after the message, because it has no data. A long-running service might try a backup path instead.
Common mistakes:
- Putting the whole loop inside one
tryblock. The first bad line then ends the loop and the rest of the file is never read. - Catching
Exceptioninstead ofValueError. A typo such asreadings.apend(value)inside thetryblock raises anAttributeError, and every line is then reported as a bad line. - Dividing by
len(lines)instead oflen(readings). The mean then counts the 3 broken lines as zeros.
Example 3 — Parse messy prices and raise clear errors
Section titled “Example 3 — Parse messy prices and raise clear errors”Goal: The unit_price column of data/sales_raw.csv holds text such as "$79.99" and "$1,299.00", plus missing-value tokens. Write a parser that returns a float or raises a ValueError with a useful message, then run it on the whole column.
Step 1 — Look at the raw values
Section titled “Step 1 — Look at the raw values”import csv
with open("data/sales_raw.csv", encoding="utf-8", newline="") as f: rows = list(csv.DictReader(f))
prices = [row["unit_price"] for row in rows]print(len(prices), "prices")print(prices[:3], prices[10:12])print("not starting with $:", sorted({p for p in prices if not p.startswith("$")}))1200 prices['$249.00', '$29.99', '$89.50'] ['$79.99', '$1,299.00']not starting with $: ['', '-', 'N/A']csv.DictReader reads each line of a CSV file as a dict whose keys are the column names (module 07 covers the csv module). Every value is a str. A set comprehension collects the distinct values that do not start with $: these are the missing-value tokens "", "-" and "N/A".
Step 2 — Write a parser that raises on bad input
Section titled “Step 2 — Write a parser that raises on bad input”MISSING_TOKENS = {"", "N/A", "-"}
def parse_price(text): """Turn "$1,299.00" into 1299.0. Raise ValueError for missing or bad text.""" cleaned = text.strip() if cleaned in MISSING_TOKENS: raise ValueError(f"unit_price is missing ({text!r})") try: price = float(cleaned.removeprefix("$").replace(",", "")) except ValueError: raise ValueError(f"unit_price {text!r} is not a price") from None if price <= 0: raise ValueError(f"unit_price must be positive, got {price}") return price
for sample in ["$79.99", "$1,299.00", "N/A", "", "$12,99", "$-5.00"]: try: print(f"{sample!r:>12} -> {parse_price(sample)}") except ValueError as err: print(f"{sample!r:>12} -> ValueError: {err}") '$79.99' -> 79.99 '$1,299.00' -> 1299.0 'N/A' -> ValueError: unit_price is missing ('N/A') '' -> ValueError: unit_price is missing ('') '$12,99' -> 1299.0 '$-5.00' -> ValueError: unit_price must be positive, got -5.0The function checks the missing tokens first, so the message says “missing” instead of “not a price”. from None hides the low-level float() error, because the new message already shows the bad text. The sample "$12,99" is a European decimal comma: removing the comma gives 1299.0, a wrong price that no exception catches. A parser can only reject what it checks for. Exercise M06-C04 asks you to add that check.
Step 3 — Run the parser on the whole column
Section titled “Step 3 — Run the parser on the whole column”parsed = []failures = {}for row in rows: try: parsed.append(parse_price(row["unit_price"])) except ValueError as err: message = str(err) failures[message] = failures.get(message, 0) + 1print(f"parsed {len(parsed)} of {len(rows)} prices")for message, count in sorted(failures.items()): print(f" {count:>2} x {message}")parsed 1190 of 1200 prices 6 x unit_price is missing ('') 2 x unit_price is missing ('-') 2 x unit_price is missing ('N/A')The data dictionary says that the column has 10 missing prices: 6 empty, 2 N/A, 2 -. The counts match, so the parser rejects exactly the missing values and nothing else.
Step 4 — Check the result
Section titled “Step 4 — Check the result”print(f"min {min(parsed)}, max {max(parsed)}")assert len(parsed) + sum(failures.values()) == len(rows)assert max(parsed) == 1299.0 # the most expensive product, the 4K TVmin 14.99, max 1299.0The asserts check facts that must be true if the code is right: every row is either parsed or counted, and the largest price is a real list price.
Common mistakes:
- Returning
0.0for a missing price. A zero price is a real-looking number: it pulls every average down and nobody notices. - Calling
float()before checking the tokens.float("N/A")gives the vague messagecould not convert string to float. - Forgetting
strip()." $79.99"with a leading space would then fail.
Example 4 — Validate sales rows with a custom hierarchy
Section titled “Example 4 — Validate sales rows with a custom hierarchy”Goal: Before a cleaning step, check every row of data/sales_raw.csv against the pipeline’s rules: required columns, no missing values, quantity from 1 to 50 (thresholds in data/config.json). Use the classes DataValidationError, MissingColumnError, MissingValueError and InvalidValueError from Custom exceptions and count the problems by type and column.
Step 1 — Check the header first
Section titled “Step 1 — Check the header first”REQUIRED_COLUMNS = [ "order_id", "customer_id", "region", "unit_price", "quantity", "discount"]
def check_columns(header, source): missing = [name for name in REQUIRED_COLUMNS if name not in header] if missing: message = f"{source}: missing columns {missing}" raise MissingColumnError(message, column=missing[0])
with open("data/sales_raw.csv", encoding="utf-8", newline="") as f: reader = csv.DictReader(f) check_columns(reader.fieldnames, "sales_raw.csv") rows = list(reader)print(len(rows), "rows, header ok")1200 rows, header okreader.fieldnames is the list of column names from the header. A missing column is a problem for the whole file, so the check runs once, before any row.
Step 2 — See a missing column fail
Section titled “Step 2 — See a missing column fail”with open("data/reports/2024-01.csv", encoding="utf-8", newline="") as f: header = csv.DictReader(f).fieldnamesprint(header)check_columns(header, "2024-01.csv")['order_id', 'order_date', 'store_id', 'product', 'category', 'quantity', 'revenue']MissingColumnError: 2024-01.csv: missing columns ['customer_id', 'region', 'unit_price', 'discount']The monthly reports are a smaller extract of the sales data with only 7 columns. The message names all four missing columns at once, so you fix them in one go instead of one per run.
Step 3 — Validate one row
Section titled “Step 3 — Validate one row”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 convert(row, column, line_number, parse): """Parse a present cell with parse(); raise InvalidValueError on bad text.""" text = require(row, column, line_number) # MissingValueError if missing try: return parse(text) except ValueError as err: raise InvalidValueError( f"line {line_number}: {column} {text!r} is not a valid value", column=column, line_number=line_number, ) from err
def validate_row(row, line_number): """Return a clean dict, or raise a DataValidationError subclass.""" clean = {"order_id": row["order_id"]} clean["customer_id"] = require(row, "customer_id", line_number) clean["region"] = require(row, "region", line_number).title() clean["unit_price"] = convert(row, "unit_price", line_number, parse_price) quantity = convert(row, "quantity", line_number, int) if not 1 <= quantity <= 50: raise InvalidValueError( f"line {line_number}: quantity {quantity} is outside 1-50", column="quantity", line_number=line_number, ) clean["quantity"] = quantity clean["discount"] = convert(row, "discount", line_number, float) return clean
clean = validate_row(rows[0], 2)print(list(clean.values()))bad_price = {**rows[0], "unit_price": "$12.9O"} # a typo: letter O for zerotests = [(rows[219], 221), (rows[577], 579), (bad_price, 2)]for row, line_number in tests: try: validate_row(row, line_number) except DataValidationError as err: print(f"{type(err).__name__}: {err}")['O000004', 'C01087', 'West', 249.0, 1, 0.1]MissingValueError: line 221: unit_price is missing ('N/A')InvalidValueError: line 579: quantity -3 is outside 1-50InvalidValueError: line 2: unit_price '$12.9O' is not a valid valuevalidate_row() returns a clean row or raises one specific error, never half-checked data. convert() checks for a missing token first, so any ValueError left over means a bad value: raise ... from err turns it into an InvalidValueError with the column. Line n of the file is rows[n - 2], because the header is line 1 and lists count from 0.
Step 4 — Validate the whole file and count the problems
Section titled “Step 4 — Validate the whole file and count the problems”clean_rows = []problems = {}examples = {}for line_number, row in enumerate(rows, start=2): try: clean = validate_row(row, line_number) except DataValidationError as err: key = (type(err).__name__, err.column) problems[key] = problems.get(key, 0) + 1 examples.setdefault(key, err.line_number) else: clean_rows.append(clean)
print(f"{len(clean_rows)} valid rows, {len(rows) - len(clean_rows)} rejected")for (error_type, column), count in sorted(problems.items()): first = examples[(error_type, column)] print(f" {error_type:<18} {column:<12} {count:>3} (first at line {first})")1117 valid rows, 83 rejected InvalidValueError quantity 10 (first at line 153) MissingValueError customer_id 23 (first at line 122) MissingValueError discount 23 (first at line 5) MissingValueError region 17 (first at line 16) MissingValueError unit_price 10 (first at line 221)One except DataValidationError clause catches all three subclasses, and the attributes give the report by type and column. A row counts once, under the first rule it broke, so discount shows 23 and not the 24 of the data dictionary: one such row also breaks an earlier rule.
Common mistakes:
- Raising a plain
Exception("bad row"). The caller cannot catch it without also catching every bug. - Catching
DataValidationErroraround the header check and the row loop together. A missing column is a reason to stop, not one more row to count. - Parsing the message text (
if "missing" in str(err)) to sort errors. Use the type and the attributes.
Example 5 — Choose between assert and raise
Section titled “Example 5 — Choose between assert and raise”Goal: A pricing function checks that a discount is a fraction from 0 to 1. See why an assert is the wrong tool for this check, and where an assert is the right one.
Step 1 — Run the function with an assert
Section titled “Step 1 — Run the function with an assert”# check_discount.py: an assert guards a rule inside a pricing function.
def discounted_price(price, discount): assert 0 <= discount <= 1, f"discount must be a fraction, got {discount}" return round(price * (1 - discount), 2)
print(discounted_price(249.00, 0.1))print(discounted_price(249.00, 10)) # a typo: 10 instead of 0.10224.1Traceback (most recent call last): File "/path/to/my-course/check_discount.py", line 10, in <module> print(discounted_price(249.00, 10)) # a typo: 10 instead of 0.10 ~~~~~~~~~~~~~~~~^^^^^^^^^^^^ File "/path/to/my-course/check_discount.py", line 5, in discounted_price assert 0 <= discount <= 1, f"discount must be a fraction, got {discount}" ^^^^^^^^^^^^^^^^^^AssertionError: discount must be a fraction, got 10The first call works. The second one stops with an AssertionError and the message. So far, the assert seems to do its job.
Step 2 — Run the same script with -O
Section titled “Step 2 — Run the same script with -O”python -O check_discount.py224.1-2241.0With the optimize flag -O, Python removes every assert statement. The typo now gives a negative price of -2241.0, with no error. Some deployment setups run Python with -O, so the check is gone exactly where it matters.
Step 3 — Raise for input that can be wrong
Section titled “Step 3 — Raise for input that can be wrong”def discounted_price(price, discount): if not 0 <= discount <= 1: raise ValueError(f"discount must be a fraction from 0 to 1, got {discount}") return round(price * (1 - discount), 2)
print(discounted_price(249.00, 0.1))print(discounted_price(249.00, 10))224.1ValueError: discount must be a fraction from 0 to 1, got 10An if with raise always runs, and a ValueError tells the caller that the argument was bad. The caller can catch it and, for example, skip the row.
Step 4 — Keep assert for invariants
Section titled “Step 4 — Keep assert for invariants”order_lines = [(249.00, 0.1), (79.99, 0.0), (129.95, 0.2)]prices = [discounted_price(price, discount) for price, discount in order_lines]print(prices)
# Invariant: a discount never raises a price. If this fails, the formula is wrong.assert all(new <= old for new, (old, _) in zip(prices, order_lines, strict=True))[224.1, 79.99, 103.96]This assert does not check the input. It checks the code: if someone changes the formula to price * (1 + discount), the assert stops the script. Without -O it catches the bug; with -O the program is no less safe than with no check at all.
Common mistakes:
- Validating function arguments, file contents or user input with
assert. - Writing
assert (condition, "message")with parentheses. That asserts a non-empty tuple, which is always true. Python shows aSyntaxWarningfor it. - Catching
AssertionErrorto handle bad data. Raise a specific exception instead.
Example 6 — Find a wrong average with breakpoint() and pdb
Section titled “Example 6 — Find a wrong average with breakpoint() and pdb”Goal: A function should return the average revenue of three order lines (224.10, 29.99 and 179.00 USD). The right answer is 144.36, but the script prints a much smaller number and no error. Find the bug with the debugger.
Step 1 — Run the script without the debugger
Section titled “Step 1 — Run the script without the debugger”# debug_total.py: the average revenue of three order lines. It has a bug.revenues = [224.1, 29.99, 179.0]
def average(values): breakpoint() # pause here and open the debugger for value in values: total = 0.0 total += value return total / len(values)
print("Average revenue:", round(average(revenues), 2))PYTHONBREAKPOINT=0 python debug_total.pyAverage revenue: 59.67The environment variable PYTHONBREAKPOINT=0 makes Python skip every breakpoint() call, so the script runs to the end. 59.67 is wrong: it is exactly 179.00 / 3, the last value divided by the count.
Step 2 — Pause and step through the loop
Section titled “Step 2 — Pause and step through the loop”Run python debug_total.py. It stops at breakpoint() and shows the (Pdb) prompt. (Python 3.13 and later stop on the breakpoint() line itself; 3.12 stops on the line after it.) Type ll, then n four times, then p value, total, then n twice, p value, total and finally c. On this page, printf types the commands for you:
printf 'll\nn\nn\nn\nn\np value, total\nn\nn\np value, total\nc\n' | python debug_total.py> /path/to/my-course/debug_total.py(6)average()-> breakpoint() # pause here and open the debugger(Pdb) 5 def average(values): 6 -> breakpoint() # pause here and open the debugger 7 for value in values: 8 total = 0.0 9 total += value 10 return total / len(values)(Pdb) > /path/to/my-course/debug_total.py(7)average()-> for value in values:(Pdb) > /path/to/my-course/debug_total.py(8)average()-> total = 0.0(Pdb) > /path/to/my-course/debug_total.py(9)average()-> total += value(Pdb) > /path/to/my-course/debug_total.py(7)average()-> for value in values:(Pdb) (224.1, 224.1)(Pdb) > /path/to/my-course/debug_total.py(8)average()-> total = 0.0(Pdb) > /path/to/my-course/debug_total.py(9)average()-> total += value(Pdb) (29.99, 0.0)(Pdb) Average revenue: 59.67> /path/to/my-course/debug_total.py(6)average() means file, line 6, function average; the -> line runs next. In the second pass, p value, total shows (29.99, 0.0): total = 0.0 ran again and threw the running total away. (Your typed commands do not appear here, because printf sent them.)
Step 3 — Fix the bug and remove the breakpoint
Section titled “Step 3 — Fix the bug and remove the breakpoint”def average(values): breakpoint() # pause here and open the debugger total = 0.0 for value in values: total = 0.0 total += value return total / len(values)Move total = 0.0 above the loop and delete the breakpoint() line. The fixed function:
def average(values): total = 0.0 # start once, before the loop for value in values: total += value return total / len(values)
result = average([224.1, 29.99, 179.0])print("Average revenue:", round(result, 2))assert abs(result - 144.36) < 0.01Average revenue: 144.36The assert locks in the right answer. Module 14 turns checks like this into tests.
Common mistakes:
- Leaving
breakpoint()in code that you commit. A scheduled job then waits forever for input. Search for it before you commit; ruff’s ruleT100flags it. - Typing a variable name that is also a pdb command, such as
corn. pdb runs the command. Usep cto print a variable calledc. - Adding prints in ten places at once. Pause once, look at all the values, then decide.
Example 7 — Log a validation step to the console and a file
Section titled “Example 7 — Log a validation step to the console and a file”Goal: The validation of Example 4 runs every night. Log a summary to the terminal, every problem to a file for later, and full tracebacks for unexpected errors. Then read the real pipeline log data/logs/app.log.
Step 1 — Change the level to see more detail
Section titled “Step 1 — Change the level to see more detail”log = logging.getLogger("sales.cleaner")log.setLevel(logging.DEBUG)log.debug("first rejected line: %d", 221)log.info("%d valid rows", len(clean_rows))log.setLevel(logging.NOTSET) # back to the root level (INFO)log.debug("this line is hidden again")DEBUG [sales.cleaner] first rejected line: 221INFO [sales.cleaner] 1117 valid rowsA logger’s own level, when set, beats the level of the root logger. NOTSET means “use the level of my parent”. In a real project you set the level from a command-line option or a config file (data/config.json has a logging key), so you get detail without editing code.
Step 2 — Send detail to a file and only warnings to the terminal
Section titled “Step 2 — Send detail to a file and only warnings to the terminal”from pathlib import Path
Path("output").mkdir(exist_ok=True) # write outputs to output/, never into data/
vlog = logging.getLogger("sales.validate")vlog.setLevel(logging.DEBUG)vlog.propagate = False # do not also pass the messages to the root handler
console = logging.StreamHandler() # stderrconsole.setLevel(logging.WARNING)console.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
to_file = logging.FileHandler("output/validation.log", mode="w", encoding="utf-8")to_file.setLevel(logging.DEBUG)to_file.setFormatter(logging.Formatter("%(levelname)-8s %(name)s %(message)s"))
vlog.addHandler(console)vlog.addHandler(to_file)
vlog.info("validating %d rows", len(rows))rejected = 0for line_number, row in enumerate(rows, start=2): try: validate_row(row, line_number) except DataValidationError as err: vlog.debug("%s: %s", type(err).__name__, err) rejected += 1if rejected: vlog.warning( "%d of %d rows rejected, see output/validation.log", rejected, len(rows) )WARNING 83 of 1200 rows rejected, see output/validation.logThe terminal shows one line, because its handler drops everything below WARNING. Path("output").mkdir(exist_ok=True) creates the folder if it is missing (module 07). propagate = False stops the messages at this logger; without it, the root handler from earlier would print each one a second time.
Step 3 — Read the log file
Section titled “Step 3 — Read the log file”to_file.close()with open("output/validation.log", encoding="utf-8") as f: log_lines = f.read().splitlines()print(len(log_lines), "lines in output/validation.log")for line in log_lines[:4]: print(line)print(log_lines[-1])85 lines in output/validation.logINFO sales.validate validating 1200 rowsDEBUG sales.validate MissingValueError: line 5: discount is missing ('')DEBUG sales.validate MissingValueError: line 16: region is missing ('N/A')DEBUG sales.validate MissingValueError: line 40: region is missing ('N/A')WARNING sales.validate 83 of 1200 rows rejected, see output/validation.logThe file has the INFO line, one DEBUG line per rejected row and the final WARNING. The level names are padded to 8 characters by %(levelname)-8s, so the messages line up.
Step 4 — Log an unexpected error with its traceback
Section titled “Step 4 — Log an unexpected error with its traceback”# log_exception.py: log a failed conversion with its traceback, then carry on.import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s [%(name)s] %(message)s")log = logging.getLogger("loader")
raw_values = ["21.7", "n/a", "22.4"] # lines 1-3 of a readings filereadings = []for line_number, raw in enumerate(raw_values, start=1): try: readings.append(float(raw)) except ValueError: log.exception("line %d: cannot parse %r", line_number, raw)log.info("parsed %d of %d values", len(readings), len(raw_values))ERROR [loader] line 2: cannot parse 'n/a'Traceback (most recent call last): File "/path/to/my-course/log_exception.py", line 11, in <module> readings.append(float(raw)) ~~~~~^^^^^ValueError: could not convert string to float: 'n/a'INFO [loader] parsed 2 of 3 valueslog.exception() logs at ERROR level and adds the traceback of the exception that is being handled. Call it only inside an except block. The program goes on; the log keeps the full story for later.
Step 5 — Count the levels in a real log
Section titled “Step 5 — Count the levels in a real log”LEVEL_NAMES = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}levels = {}with open("data/logs/app.log", encoding="utf-8") as f: app_lines = f.read().splitlines()for line in app_lines: parts = line.split(" ", 3) # date, time, level, rest if len(parts) == 4 and parts[2] in LEVEL_NAMES: levels[parts[2]] = levels.get(parts[2], 0) + 1print(len(app_lines), "lines:", levels)for line in app_lines[143:148]: print(line)500 lines: {'INFO': 447, 'DEBUG': 13, 'WARNING': 25, 'ERROR': 7}2024-05-01 10:53:56,110 ERROR [loader] Failed to parse data/reports/2024-04.csvTraceback (most recent call last): File "pipeline/loader.py", line 58, in load_report df = pd.read_csv(path, usecols=EXPECTED_COLUMNS)ValueError: Usecols do not match columns, columns expected but not found: ['quantity']The counts add up to 492, not 500: the other 8 lines are two tracebacks that log.exception() wrote under ERROR lines. Read them like any traceback: the last line names the column that the loader could not find in the April report.
Common mistakes:
- Calling
logging.basicConfig()in a module that others import. It configures the whole program; do it once, in the main script. - Building messages with f-strings:
log.debug(f"row {row}")formats the text even whenDEBUGis off. Pass arguments:log.debug("row %s", row). - Forgetting
propagate = Falseafter you add handlers to a named logger. Each line then appears twice. - Logging a caught exception with
log.error(err). You lose the traceback. Uselog.exception(...).
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| Reading a traceback from the top | You look at the start of the program, far from the error | Start at the last line, then the last frame of your own code |
| Fixing the last frame by reflex | The bug comes back with the next bad row | Walk up the frames; fix where the bad value entered |
A bare except: |
Ctrl+C does not stop the script; bugs vanish | Catch the specific types you expect |
except Exception: around a whole function |
A typo returns None and no error appears |
Keep the try block to the one line that can fail |
except Exception before except ValueError |
The ValueError clause never runs |
Order clauses from specific to general |
try around the whole loop |
The first bad line ends the loop | Put try inside the loop, around the conversion |
Returning 0 or "" for bad data |
Averages and counts are quietly wrong | Raise, or return None and count the skipped rows |
raise Exception("bad") |
Callers cannot catch it without catching every bug | Raise a specific built-in or custom type |
| A message without context | ValueError: bad value |
Say where, what and why: line 579: quantity must be at least 1, got -3 |
raise New(...) in except without from |
Traceback says “During handling of the above exception, another exception occurred” | Write raise New(...) from err |
assert to validate input |
Bad data passes under python -O |
if not ok: raise ValueError(...) |
assert (x > 0, "msg") |
The assert never fails; SyntaxWarning |
assert x > 0, "msg" |
breakpoint() left in the code |
A scheduled job hangs, waiting for input | Remove it; run with PYTHONBREAKPOINT=0 to check |
log.debug(...) shows nothing |
No output at all | Lower the level: basicConfig(level=logging.DEBUG) or log.setLevel(...) |
| Each log line printed twice | Duplicate lines | propagate = False, or add handlers only to the root logger |
log.error(err) in except |
The traceback is lost | log.exception("what failed") |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: FastAPI (module 44) turns invalid request data into an HTTP 422 response with the pydantic error details, and an unexpected exception into a 500 response with the traceback in the server log.
- Automation: a backup script retries a network copy on
ConnectionError, logs each attempt and usesfinallyto remove a lock file, so the next run can start. - Command-line tools: a CLI catches its own custom errors at the top, prints one clear line instead of a traceback and exits with a non-zero code, so shell scripts can see the failure.
- Tooling: pytest (module 14) reports a failing
assertwith the values on both sides, and libraries define hierarchies such asrequests.exceptions.RequestExceptionso you can catch one family of errors.
Summary
Section titled “Summary”- A syntax error stops the program before it runs. An exception happens while it runs and can be handled.
- Read a traceback from the bottom: the last line says what, the last frame says where, the frames above say how the program got there. The bug is often where the bad value entered, higher up.
- Built-in exceptions form a hierarchy.
except LookupErrorcatchesKeyErrorandIndexError;Exceptionis the base of every error you should handle. try/excepthandles an exception. Catch specific types, keep thetryblock small, useas errfor details.elseruns on success,finallyalways.raisesignals a problem with a clear message: where, what, why. A bareraisere-raises.raise ... from errchains a clear error to its cause.- A custom exception hierarchy (
DataValidationErrorand its subclasses) lets callers catch one problem or the whole family, and carry data such as the column. assertchecks invariants of your own code and disappears under-O. Useraisefor data and input.- Debug in steps: reproduce, read, inspect, pause with
breakpoint(), fix, then lock in the fix with an assert or a test. logginggives each message a level, a format and a destination. Use named loggers,%sarguments andlog.exception()inexceptblocks.
Self-check questions
Section titled “Self-check questions”Q1. A traceback has five frames. Which line do you read first, and which frame do you look at next?
Answer
Read the last line first: it names the exception type and its message. Then look at the last frame, where the exception was raised. If that frame is inside a library, walk up to the first frame from your own code. Then keep walking up to find where the bad value came from.
Q2. What is the difference between a SyntaxError and a ValueError?
Answer
A SyntaxError means that the code is not valid Python. Python finds it before it runs any line, and no try can handle it inside the same file: you fix the code. A ValueError is an exception at run time: the code is valid but a value is unusable, as in float("N/A"). You can catch it with try/except.
Q3. Does except LookupError: catch a KeyError? Does except ValueError: catch a TypeError?
Answer
Yes to the first: KeyError is a subclass of LookupError. No to the second: TypeError and ValueError are separate subclasses of Exception. Use except (ValueError, TypeError): to catch both.
Q4. In what order do the clauses run when the try block succeeds? And when it raises a ValueError that an except ValueError clause handles?
Answer
Success: try, then else, then finally. Handled ValueError: try (up to the failing line), then except ValueError, then finally. finally runs in every case, even after a return.
Q5. Why is except Exception: return None around a whole function body a bad idea?
Answer
It catches every error, including your own bugs such as a NameError from a typo or an AttributeError. The function then returns None for every call and nothing tells you why. Catch only the exception you expect, around only the line that can raise it.
Q6. What does raise InvalidValueError(msg) from err add, compared with raise InvalidValueError(msg)?
Answer
It stores the original exception in __cause__ and marks the link as deliberate. The traceback shows both errors, joined by “The above exception was the direct cause of the following exception”. Without from, Python still shows both, but with “During handling of the above exception, another exception occurred”, which reads like a bug in the handler.
Q7. Why does the course define MissingColumnError, MissingValueError and InvalidValueError as subclasses of one DataValidationError?
Answer
A caller can then choose: catch one specific problem (except MissingColumnError: to stop the run), or catch the whole family with except DataValidationError: to count bad rows. The base class also holds shared attributes such as column and line_number, and no validation error is mixed up with an unrelated bug.
Q8. A function checks its discount argument with assert 0 <= discount <= 1. What goes wrong, and what should it do instead?
Answer
Under python -O every assert is removed, so a discount of 10 passes and the price becomes negative. The error type is also always AssertionError, which says “bug” rather than “bad argument”. Write if not 0 <= discount <= 1: raise ValueError(...). Keep assert for invariants of your own code.
Q9. In a pdb session, what do n, s, c and p total do?
Answer
n runs the current line and stops at the next line of the same function. s steps into a function that the line calls. c continues until the next breakpoint or the end of the program. p total prints the value of total.
Q10. A script calls log.info("loaded %d rows", 1200) and nothing appears. Why? Give two ways to fix it.
Answer
The default level is WARNING, so INFO messages are dropped. Fix it with logging.basicConfig(level=logging.INFO) at the start of the main script, or with log.setLevel(logging.INFO) on the logger, provided a handler with a low enough level is attached (for example the one basicConfig() creates).
Q11. Why should log messages use log.debug("row %s", row) instead of log.debug(f"row {row}")?
Answer
With %s arguments, logging builds the text only when the message is really shown. With an f-string, Python builds the text first, even when DEBUG is switched off. In a loop over 20,000 rows, that wasted work adds up. Linters such as ruff flag f-strings in logging calls.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 26 exercises with hints and full solutions, from naming exceptions to validating a whole sales file.
- Mini-project: build a validation script for
data/sales_raw.csvwith a custom exception hierarchy and logging. - Cheat sheet: exceptions,
tryforms,raise, pdb commands and logging setup on one page. - Next module: 07. Files and data formats teaches
pathlib,openandwith, CSV, JSON and processing a folder of files.