Definition
Debugging is finding and fixing the cause of wrong behaviour. Python's main tools are reading the traceback, adding print or logging statements, and using a debugger such as breakpoint() (pdb) or the one in VS Code, which pauses the program so you can inspect it.
In simple words
A traceback isn't a scolding, it's directions. Read from the bottom: the last line says what went wrong, and the lines above say where. A debugger is a pause button for your code.
Why it matters
Professional programmers spend a large share of their time debugging. In ML, the bug is often not a crash but a quietly wrong result.
How it works
- Reproduce it, with the smallest input you can.
- Read the error from the bottom up.
- Form a guess about the cause.
- Check it, by printing a value or setting a breakpoint.
- Fix it, then add a test so it stays fixed.
| pdb command | Does |
|---|---|
| n | Next line |
| s | Step into a function |
| c | Continue |
| p x | Print x |
| q | Quit |
In code
The bug here gives no error at all, which is the hard kind. Printing the values reveals it.
def average(numbers):
total = 0
for n in numbers:
total = n # the bug: should be total += n
return total / len(numbers)
marks = [10, 20, 30]
print("Result:", average(marks), " Expected:", sum(marks) / len(marks))
def average_traced(numbers):
total = 0
for n in numbers:
total = n
print(" n =", n, "total =", total)
return total / len(numbers)
average_traced(marks)Output
Result: 10.0 Expected: 20.0 n = 10 total = 10 n = 20 total = 20 n = 30 total = 30
Common mistakes
- Changing code at random until it works. You won't know why, and it'll come back.
- Reading only the top of a long traceback. The real error is at the bottom.
Check yourself
Summary
- Read tracebacks from the bottom.
- Guess, check and fix, rather than changing things at random.
- breakpoint() pauses your program.
Finished reading?
Sources: Python docs: pdb