Thursday, August 2, 2007

Beginner Python Debugging

While I won't go into all the details and best practices of Python debugging here (because I do not know them), Chris Blunck shared a very easy and useful method with me that can be used in many situations. First, the code:
import pdb
pdb.set_trace()
That's it. All you have to do is put those two lines just before a line where, for example, an error is being thrown, or where you are not sure what the state of things is. pdb is the "Python Debugger", appropriately enough. There are several ways to invoke and use this module, other than what I listed above. The format I gave is most useful for setting a breakpoint. When your code runs and reaches where you have placed those two lines, you enter the debugging command line. You can check variable values as they exist at the breakpoint, execute code, whatever you want to try to understand the error you are examining.

An example:
>>> list = [1,2,3,4,5,6]
>>> import pdb
>>> pdb.set_trace()
--Return--
> (1)()->None
(Pdb) print list[2]
3
As can be easily seen in this very simple case, once the breakpoint is reached and one enters the debugging command line, it is trivially easy to, for example, verify variable values as compared to what you were expecting them to be. If desired, you can also continue executing the code after the breakpoint by pressing "c" on the pdb command line.

For details on other ways to use pdb, see the official doc. This separate guide has very useful information for Python debugging, specifically with pdb, for beginners.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home