Cheap debugging trick: inspect + pprint

by Uche Ogbuji

When I recommended one of my pet Python debugging tricks to my brother, I realized maybe others would have missed these odd but useful bits of the Python standard library.

Inspect provides all sorts of juicy introspection goodies, including the current call stack. pprint is the key to making some visual sense of the __repr__ of a large dictionary, tuple or dictionary. I often use pprint to tame the stack trace list output from inspect.stack(). You can do the same sort of thing with exceptions and the traceback module, but I think inspect+pprint is the quickest way to figure out where those rogue calls to CrashMe() are coming from. Here's an example:

>>> import inspect
>>> import pprint
>>> def a():
... b()
>>> def b():
... c()
>>> def c():
... pprint.pprint(inspect.stack())
>>> a()
[(, '', 2, 'c', None, None),
(, '', 2, 'b', None, None),
(, '', 2, 'a', None, None),
(, '', 1, '?', None, None)]


2004-07-15 06:26:28
The traceback module

traceback.print_stack() is another handy debugging tool.