Breaking into a debugger in Python

Published:

This is probably old news to most folks, but I only found out about this recently, more than twelve years into being a Python programmer.

The pdb (Python Debugger) module has a few useful functions. For years I've been using pdb.pm(), the postmortem debugger. It can be run from the Python shell to invoke a debugger after an exception. Traditionally I've done:

% python -i myscript.py
(some exception occurs)
>>> import pdb
>>> pdb.pm()
(Pdb) 
But for this to work you need to be able to pass arguments to the interpreter (-i) and the code needs to throw an exception that isn't caught.

Enter pdb.set_trace(). It begins the same interactive debugger that pdb.pm() provides upon request, from code. So in the middle of a function that's confusing me I add:

from pdb import set_trace;set_trace()
and my code will stop, ready for me to tear apart its runtime state. I just wish it had a more descriptive name so that I'd have found it earlier.

Bonus: printing stack traces Python's stack traces in exceptions are pretty useful. It used to be difficult to get the current stack in Python, involving raising and catching an exception. Now the traceback module has traceback.print_stack() and traceback.extract_stack() methods.