Fri
Jul 9

Python snippet: nicer Python tracebacks

Python exceptions are really helpful but they're also rather ugly. Here's a mean one I encountered today. Don't try to interpret it -- it's only here to show off its ugliness:

I wanted it to look more like this:

So I wrote some code to do that. Specifically, the exception formatter I wrote does the following:

  1. Prints only the 5 deepest stack frames (older frames are usually noise)
  2. Prints code from only the 3 deepest stack frames (same reasoning)
  3. Prints as little of the file name as possible -- the .py suffix is removed, as is any directory information above the current working directory
  4. Prints file names and method names lined up, one after the other. Note that the messy traceback above almost does this already, but that's just luck.
  5. If Pygments is installed, syntax-highlights the code.

All of the above is, of course, configurable.

Here's the code:

bettertb.py

Usage:

import bettertb
bettertb.run(your_main_function, arg1, arg2, ...)

This is a pretty quick and dirty work in progress, so email me (nicholas at lardcave) if you have suggestions, fixes, etc. The first major problem is that getting tracebacks is now more rewarding than having the code finish successfully.