Breaking out of the Code!

In the 10 years, I’ve been a professional programmer, one of the most powerful tricks I picked up was the use of the breakpoint library which is built into Python. I mean pdb module of course!

What makes this so powerful is that it will drop into an interactive python shell, allowing for a quick inspection of all objects at that breakpoint as well as a quick way to prototype and iterate on any broken code.

This has saved my bacon on more than production and I’ve been a big evangelist of it ever since learning about it back at MPC London.

How it works is simple, just by adding the line “import pdb; pdb.set_trace()” where I might set a breakpoint in an IDE, and running the code, the python terminal will break when it hits it. What’s fantastic about it is that once it’s broken it’s able to traverse up and down the stack, import modules, set variables, define new classes, monkey patch functions and just generally run any python code.

Lets see it in action:

import sys

pyPath = ",".join(sys.path)
import pdb; pdb.set_trace()

for section in pyPath.split(","):
    print section 

Running this simple example, we get dumped out on line 6

Once the code has broken, pdb will take a variety of commands to control, the most common ones are

n – run to next line
c – continue
b # – break on line number #
s – step into the current function
u – go up the calling function
a – prints the args and kwargs, if in a function
pp – pretty print

To aid in inspecting the current python frame, a common technique i use is calling dir on an object, this will print all the members of that object. 

This is a great way to quickly write code without having to reload or rerun large code chunks.

There is a remote version of pdb called rpdb, which connects via putty in the same fashion and its great for debugging code running on a remote farm or in a process which doesn’t like pdb, like many Autodesk products.

I’ve found that combining this with an except hook to only trigger the breakpoint when the code errors out has saved countless hours of debugging allowing me to get straight to the root of the issue, within the situation and environment which causes it!

A very simple and yet an exceptionally powerful module!
Happy Breakpointing!

– Geoff Samuel