the full guide

Debugging

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.

8 min Intermediate

What you need: The earlier topics of this module.

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

  1. Reproduce it, with the smallest input you can.
  2. Read the error from the bottom up.
  3. Form a guess about the cause.
  4. Check it, by printing a value or setting a breakpoint.
  5. Fix it, then add a test so it stays fixed.
pdb commandDoes
nNext line
sStep into a function
cContinue
p xPrint x
qQuit

In code

The bug here gives no error at all, which is the hard kind. Printing the values reveals it.

debugging.py
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

Question 1

1. Where do you start reading a traceback?

Question 2

2. What does breakpoint() do?

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