Debugging (notes)

last update: 2017-06-08

Essentially, there are two ways of debugging Python source code. You can either use coordinated print statements or a proper debugger. In either case, you should start by making an educated guess on where the problem is hidden. Once you've identified a potentially problematic function, add

print(locals(), "\n")

as the first line after the function's docstring as well as the last line before any return statements. Then, execute the program with input that is known to produce unexpected results. If the function arguments are wrong, your problem is higher up the call stack. If the return values are incorrect, the function is responsible for the problem. If neither is unexpected, you need to keep looking for the problem elsewhere. As an alternative to using print(.), you could also use a logging function configured to log output when in debugging mode.

For those preferring not to use print(.), a debugger is a great way of finding problems in source code. To do so, you can choose between the command-line debugger

pdb3 pyfile [arg] ...

or a debugger made available by your IDE. However, Python also allows to start the debugger right where you expect an error to be. To do so, import the pdb module and use it's set_trace() function.

import pdb

# ...
# this is where you expect things to go wrong
pdb.set_trace()

When you then execute the program as usual, Python will stop when it encounters the set_trace() call and will start the debugger at the current state of the program. To get help for pdb, use its built-in help system

(Pdb) h

A useful hint for the command-line debugger is that pressing the enter key on an otherwise empty command-line will repeat the last command. If you don't like the command-line debugger but don't have an IDE providing an interface to pdb, you could also use idle3 with the -d (debug mode) command-line flag.

idle3 -d -r your_program.py [your program's options]