typenil

Matt White

developer

typenil

developer

Print Tracebacks From Python Exception Instances

The solution:

import traceback; traceback.print_tb(exception_instance.__traceback__)

The rest:

In my daily work, I use pdb pretty heavily for debugging. There are some limitations to the pdb shell that are constant annoyances to me - one of which applies directly to my habit of sticking breakpoints in try/except blocks. For example:

class ExistentialCrisis(Exception):
    pass

def think_about_existence():
    raise ExistentialCrisis("oblivion is inevitable")

try:
    think_about_existence()
except ExistentialCrisis as exc:
    import pdb; pdb.set_trace()
    # This is where we end up in pdb after running this code.
    raise

If we weren’t in pdb, we could solve this pretty easily:

...
try:
    think_about_existence()
except ExistentialCrisis as exc:
    import traceback
    traceback.print_exc()
    raise

And you can do the same traceback.print_exc() in pdb if you use the interact command to drop into the current scope - but I inexplicably hate doing that.

How can you get the traceback from the exception object itself?

import traceback; traceback.print_tb(exc.__traceback__)
Join me in becoming a little less terrible every day.