Python Testing and Debugging · Lesson 127 of 149

Python Debugging with print and pdb

What you will learn

  • A method for finding bugs
  • Print debugging done well: f"{x=}", repr, pprint, stderr
  • The pdb debugger: breakpoint(), commands, post-mortem
  • Turning breakpoints off
  • Common kinds of bugs

1. Bugs are normal

Every program has bugs. A bug is a difference between what the code does and what you meant. Debugging is the work of finding and fixing it. It is a skill with a method, not luck.

  1. Reproduce it. Find the smallest input that makes the bug appear, every time.
  2. Read the error if there is one (traceback, lesson 14.2). Start at the bottom.
  3. Narrow down where things go wrong: which function, which line, which value is the first to be wrong?
  4. Form a hypothesis: "I think best starts too high."
  5. Test it with a print or a debugger. Do not guess blindly or change many things at once.
  6. Fix the cause, not the symptom, then re-run the failing case and the others.
  7. Add a test so the bug cannot return (lessons 18.2 and 18.3).

Often the bug is not where the error appears: a wrong value created earlier travels on and only fails later. Search backwards for the first wrong value.

Quick check: in a traceback, where do you start reading?

At the last line (what happened), then upwards to the lines in your own code (where).

2. Print debugging

The simplest tool is print. Used carefully, it is very effective.

Show the name with the value

Since Python 3.8, an f-string with = prints the expression and its value (lesson 4.5):

x, name = 7, "Rina"
print(f"{x=}", f"{name=}", f"{x * 2=}", f"{name!r}")
x=7 name='Rina' x * 2=14 'Rina'

Tips:

  • Print before and after the suspicious line, and inside loops.
  • Label each print so the output is readable: print(f"enter f({n=})").
  • Use repr (!r) to reveal hidden characters: repr("a\nb") shows 'a\nb', and a trailing space or newline becomes visible. repr(0.1 + 0.2) shows 0.30000000000000004.
  • Check types as well: type(x) (a number that is really a string is a classic).
  • For big nested data, pprint formats it over several lines:
import pprint

d = {"users": [{"id": i, "name": f"user{i}", "tags": ["a", "b", "c"]} for i in range(3)],
     "meta": {"count": 3}}
pprint.pprint(d, width=50)
{'meta': {'count': 3},
 'users': [{'id': 0,
            'name': 'user0',
            'tags': ['a', 'b', 'c']},
           {'id': 1,
            'name': 'user1',
            'tags': ['a', 'b', 'c']},
           {'id': 2,
            'name': 'user2',
            'tags': ['a', 'b', 'c']}]}
  • Send debug output to the error stream with print(..., file=sys.stderr) so that it does not mix with real output.

The limits of print

Prints are quick, but you must edit the code, re-run, and remember to delete them. For anything that is not obvious, use a debugger (next section), or the logging module (lesson 17.9) for messages you want to keep.

3. The pdb debugger

pdb is Python's built-in debugger. It lets you stop the program at a chosen line and look around: see variables, run the code one line at a time, and walk up the call chain, without editing the code with prints.

Starting it

  1. Write breakpoint() in the code where you want to stop. When Python reaches it, it opens the debugger (a prompt (Pdb)):
def mean(values):
    total = 0
    for v in values:
        total += v
    breakpoint()
    return total / len(values)

print(mean([2, 4, 6]))
  1. Or run the whole script under the debugger: python -m pdb script.py.

A short session on the code above (the commands after each (Pdb) were typed; the line after is the answer):

> dbg.py(5)mean()
-> breakpoint()
(Pdb) p total
12
(Pdb) p values
[2, 4, 6]
(Pdb) n
> dbg.py(6)mean()
-> return total / len(values)
(Pdb) p total / len(values)
4.0
(Pdb) c
4.0

The line starting with -> is the line that will run next. p total printed 12, n moved on one line, p can evaluate any expression, and c continued to the end, so the program printed its result, 4.0.

The most useful commands

Command Meaning
p expr / pp expr print (or pretty-print) an expression
n (next) run the current line; step over function calls
s (step) step into a function call
c (continue) run until the next breakpoint or the end
r (return) run until the current function returns
l / ll list the code around the current line / the whole function
w (where) show the call stack
u / d move up / down one level of the call stack
b 12 / b func set a breakpoint at line 12 / at a function
cl clear breakpoints
h / h cmd help
q quit

Typing any other text, such as total = 0 or len(values), runs it as Python in the current context. (A variable with the same name as a command, such as c or n, needs p c to print it.)

Breakpoints from the command line: running python -m pdb dbg.py and typing b 6 then c stopped at line 6, and l listed the code with the arrow -> at the current line and a B marking the breakpoint:

  4             total += v
  5  ->     breakpoint()
  6 B       return total / len(values)
  7     print(mean([2, 4, 6]))

Post-mortem debugging

When a program crashes, you can open the debugger at the moment of the crash and inspect the values that caused it. Run the script with python -m pdb -c continue script.py: it runs normally, and on an uncaught exception it stops in the debugger on the failing line. With this script, buggy.py:

def average(values):
    total = 0
    for v in values:
        total += v
    return total / len(values)

def report(groups):
    for name, values in groups.items():
        print(name, average(values))

report({"a": [1, 2, 3], "b": []})

the run printed the first result, then the traceback, then:

a 2.0
Uncaught exception. Entering post mortem debugging
> buggy.py(5)average()
-> return total / len(values)
(Pdb) p values
[]
(Pdb) p len(values)
0
(Pdb) u
> buggy.py(9)report()
-> print(name, average(values))
(Pdb) p groups
{'a': [1, 2, 3], 'b': []}
(Pdb) d
> buggy.py(5)average()

(Lines show only the file names, shortened.) The values immediately explain the ZeroDivisionError: group b is empty. u moved up to the caller, where groups is visible. In an interactive Python session you can call import pdb; pdb.pm() after an error to do the same.

Turning breakpoints off

Forgetting a breakpoint() in code is dangerous: a program running unattended would stop and wait. Setting the environment variable PYTHONBREAKPOINT=0 makes every breakpoint() do nothing (the earlier script ran straight through and printed 4.0). Still, remove them before you commit. Editors such as VS Code and PyCharm offer a graphical debugger with the same ideas (breakpoints, stepping, watching variables) and a click instead of n.

4. Usual suspects

Kind of bug Typical sign
off-by-one the last item is missed, or an index error at the end (range(n) stops at n - 1)
wrong starting value a minimum starting at 0, a count starting at 1
mutable default or shared list values from an earlier call appear (lesson 11.9)
modifying a list while looping items skipped (lesson 7.5)
= versus ==, is versus == conditions that act strangely
wrong type "5" + 1, input that is text, not a number
integer and float surprises 0.1 + 0.2, // versus / (lesson 3.4)
empty input max([]), division by len(values)
name shadowing a variable named list, sum or max hides the built-in
files and paths wrong working folder, wrong encoding (lesson 15.1)

Ask what changed since it last worked, and what you assumed. Explaining the problem aloud to someone (or to a rubber duck, a famous trick) often reveals the wrong assumption.

Worked example: the running maximum that was always zero

running_best should return the best score seen so far after each score. It works for positive scores, but not for negative ones.

def running_best(scores):
    """Return the best score seen so far after each score."""
    best = 0
    result = []
    for s in scores:
        if s > best:
            best = s
        result.append(best)
    return result

print(running_best([3, 8, 5, 9]))
print(running_best([-4, -2, -9]))
[3, 8, 8, 9]
[0, 0, 0]

Step 1: reproduce. The smallest failing case is [-4, -2, -9]; expected [-4, -2, -2].

Step 2: narrow down with prints. A print at the top of the loop shows both values:

for s in scores:
    print(f"  {s=} {best=}")
  s=-4 best=0
  s=-2 best=0
  s=-9 best=0
[0, 0, 0]

best never changes: -4 > 0 is false.

Step 2, alternative: the debugger. With python -m pdb, the commands b 5 (break at the if line), c, p s, best:

(Pdb) p s, best
(-4, 0)
(Pdb) c
(Pdb) p s, best
(-2, 0)

The same finding: best starts at 0, which is higher than every score.

Step 3: hypothesis and fix. The starting value is wrong. Use None for "nothing seen yet":

def running_best_fixed(scores):
    best = None
    result = []
    for s in scores:
        if best is None or s > best:
            best = s
        result.append(best)
    return result

print(running_best_fixed([-4, -2, -9]), running_best_fixed([3, 8, 5, 9]), running_best_fixed([]))
[-4, -2, -2] [3, 8, 8, 9] []

Step 4: re-run every case, including the earlier working one and the empty list (a new edge case that deserves a test, lesson 18.2).

Lesson from the example
the bug was a wrong starting value from the list of usual suspects
the first wrong value was best, not the result find the first wrong value
one change at a time the fix touched only the starting value and the comparison
positive test data hid the bug test negatives, empty input and single items

The scores are made up.

Common mistakes

  • Changing code at random hoping that something works.
  • Not reproducing the bug first.
  • Fixing several things at once, so you do not know which change mattered.
  • Leaving print or breakpoint() in finished code.
  • Reading only the last traceback line and not the code it points to.
  • Trusting assumptions instead of checking values.
  • Never writing a test for a bug you fixed.
  • Debugging when tired; a break often helps more than another hour.

Key takeaways

  • Debug with a method: reproduce, read the error, narrow down, hypothesise, test, fix, re-test.
  • print(f"{x=}"), repr and pprint make print debugging informative; remove them afterwards.
  • breakpoint() or python -m pdb opens the debugger; learn p, n, s, c, l, w, u, d, b, q.
  • python -m pdb -c continue script.py stops at a crash for post-mortem inspection.
  • PYTHONBREAKPOINT=0 disables breakpoints.
  • Look for the first wrong value, and know the usual suspects: off-by-one, wrong starting value, wrong type, empty input.

Practice

1. Print the variable total with its name using an f-string.

Show answer

print(f"{total=}")

2. What is the difference between the n and s commands in pdb?

Show answer

n (next) runs the current line without entering any function it calls; s (step) goes into the called function.

3. How can you stop at line 12 of a script without editing it?

Show answer

Run python -m pdb script.py, then type b 12 and c.

4. What does u do in the debugger?

Show answer

Moves up one level in the call stack, to the caller, so you can inspect its variables (d moves back down).

5. Why was the running maximum [0, 0, 0] for negative scores?

Show answer

best started at 0, and no negative score is greater than 0, so it never changed.

6. How do you make breakpoint() calls do nothing without editing the code?

Show answer

Set the environment variable PYTHONBREAKPOINT=0 before running the program.