The joy of pdb.set_trace()
I’ve never been one for debuggers, I’m too lazy really and because I’ve been a web application developer all these years, debuggers aren’t really very often found. I’m much happier just slapping a print statement or two into the code. But I may have found a way to use a debugger that suits my (primitive) working style.
First of all, it’s worth showing just how easy it is to get started with my debugger, pdb
. Add these lines to any stretch of Python.
import pdb
pdb.set_trace()
When the interpreter runs into pdb.set_trace()
, it’ll drop into the pdb
prompt and you can start inspecting the innards of your code. See the pdb
command documentation for everything you can do.
Use test cases to debug web apps
A simple trick for making use of the debugger in a web application is to use a test case as the container instead of the web server. In Django’s testing framework for example, tests are run inside the standard Python unittest
module which works happily with pdb
.
You can also set IPython to invoke pdb
whenever an exception is raised and not caught. Allowing you to debug as you play with your code in a interactive Python session.