Debugging and testing · 2 / 14 Theory

Debugging: traces, logging and debugger

Debugging is finding and fixing the cause of an error. It does not consist of trying things at random: it is a method.

The method

  • Reproduce the error: find the smallest input that causes it.
  • Locate where the program goes wrong: what did you expect and what happens?
  • Form a hypothesis about the cause.
  • Check the hypothesis by looking at the real values of the variables.
  • Fix one thing at a time and test again.

Traces with print

The simplest tool is showing the values of the variables at key points:

def sum_digits(n):
    total = 0
    for digit in str(n):
        total += int(digit)
        print(f"  digit={digit} total={total}")
    return total

print(sum_digits(1234))
#   digit=1 total=1
#   digit=2 total=3
#   digit=3 total=6
#   digit=4 total=10
# 10

Practice with Tracing a loop. Two useful tricks:

x = 42
name = "Ana"

print(f"{x=}")           # x=42
print(f"{name=}")        # name='Ana'
print(repr("hello "))   # 'hello '  (repr shows the spaces and the quotes)

f"{x=}" shows the name and the value. repr reveals invisible details, such as a trailing space in a text. When you finish, remove the traces.

logging: professional traces

The logging module is like print, but with levels of importance and the possibility of turning them on or off without touching the code:

LevelWhat for
DEBUGDetails for debugging
INFONormal facts: "server started"
WARNINGSomething odd, but the program carries on
ERRORSomething has failed
CRITICALSerious failure
import logging
import sys

logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s", stream=sys.stdout, force=True)

logging.debug("internal detail")        # not shown: DEBUG < INFO
logging.info("server started")          # INFO: server started
logging.warning("low space")            # WARNING: low space
logging.error("could not save")         # ERROR: could not save

Changing level=logging.INFO to logging.DEBUG would show all the messages, and to logging.ERROR only the serious ones. In a real program, a single change replaces hundreds of print calls. Practice with Logging records.

The debugger: breakpoint()

A debugger stops the program at a point and lets you inspect it. In Python it is enough to write breakpoint():

def average(items):
    total = sum(items)
    breakpoint()          # the program stops here
    return total / len(items)

In the terminal the (Pdb) prompt appears, where you can type commands:

CommandDoes
p variableShows the value of a variable
n (*next*)Runs the next line
s (*step*)Steps into the function on the line
c (*continue*)Continues until the next stop point or the end
l (*list*)Shows the code around the current line
q (*quit*)Leaves the debugger

Editors such as VS Code or PyCharm offer a graphical debugger: you set a breakpoint by clicking next to the line number and advance step by step watching the variables in a panel. It is the most comfortable way to debug large programs.

A classic mistake: debugging without understanding

Changing things "to see if it works" almost never fixes anything: it usually hides the symptom or creates a new bug. Before touching the code, make sure you understand why it fails. Explaining the problem out loud (to a colleague, or to a rubber duck, the *rubber duck* technique) often reveals the answer.