Site Section:
Keywords:
I am afraid that in practice I have always ended up going the simple "litter the code with print
statements" route when debugging my Python. Without the compilation step, the cost of inserting and then removing these lines from the source code is relatively cheap, and has served me well enough so far. Thus, as sanctioned under the "if it is not broken, don't fix it" clause, I have not felt the need to look any further, or look into learning how to use pdb
. If I used a bells-and-whistles glamorous IDE for development (e.g., WinPDB, PyCharm, WingIDE), I probably would take advantage of the built-in visually-oriented debuggers. But right now, I use Vim as my main development environment, and I doubt that is going to change anytime soon. So, it seemed that print
-statement based debugging was going to be around for a while to come.
Until, that is, I learned how easy using pdb
actually is. It takes just the following inserted into the desired breakpoint(s) in your code:
import pdb; pdb.set_trace();
That's it.
That's all there is to it.
Just that one line of code -- barely more characters then a minimal print
statement -- and you are in the debugging business: the execution breaks right there, and you are dropped into a deugger shell. This shell is a slightly-limited Python REPL interpreter shell enhanced with all the usual debugging commands (step, continue, bt, etc.) . It is limited in comparison to the full-fledged Python REPL interpreter shell in that multi-line statements are not possible, and some names are now used as the built-in debugger commands (which can be seen by typing '?
' or 'help
').
Knowing how simple pdb
-based debugging is, I think I am going to be using it a lot more in the future. One little plus is that there is not much chance that the character sequence "pdb.set_trace()
" plays a role in production code, so you can safely and easily strip out the debugging code in Vim by the following command:
:g /pdb\.set_trace()/d
As a bonus nugget of info, I also learned that if I wanted to invoke the full-fledged Python REPL shell anywhere in my code, all I have to do is insert:
import code; code.interact(local=locals());
at the appropriate point. Exiting the shell will resume execution of the program.