Jump to: [A] [B] [C] [D] [E] [F]

Debugging (Optional)

If you haven't settled on a debugging routine yet, here is something you might want to try out.

When working on projects you'll likely spend more time debugging than actually writing code. pdb is a useful module built in to Python for debugging that allows you to set breakpoints and step through your code line by line. While stepping through, you can examine the values of variables, run arbitrary test code, and even change values of variables. 

To use pdb, you must import it at the top of your file then insert the line pdb.set_trace() somewhere in your code. When you run the code, execution will stop as soon as it hits that line (your breakpoint) and you will enter the debugger. As an example, we'll use the following file, which we'll call breakpoints.py:

import pdb

def foo():
    a = 5
    b = [7,8,9]
    print a*b

def bar():
    a = 3
    b = "cool "
    pdb.set_trace() # This sets a breakpoint here
    foo()
    print a*b

Now run your code interactively using python -i breakpoints.py:

>>> bar()
> /Users/admin/Documents/UMD/CS421/Code_notes/breakpoints.py(12)bar()
-> foo()
(Pdb) 

You are now in the debugger! There are four main commands available to you:

In addition, you can examine the values of variables in your current environment and even modify them. Try experimenting!

For more detailed info on pdb including examples, more commands, and abbreviations for commands, consult the official documentation.

Eclipse combined with PyDev has a nice UI for debugging. PyDev installation can be messy but is possible if you persevere.