Patching Python Tracebacks
So what’s one of the greatest features Python has? Correct. Exceptions and Tracebacks. Especially the latter is a cool thing but it’s also limited. Say you have a template engine that generates code before executing the template. So if an runtime error occurs the message is correct but the line number points to the generated code and not the source line.
So how to fix? The plan basically is:
- Have a generated line <-> source line mapping somewhere
- catch exceptions that happen in the code execution and skip the first one or two frames until you reach the frame where the generated code is
- reraise the exception in a isolated namespace but in the new line (hackish)
- patch the traceback and inject your new traceback from the isolated frame (nearly impossible)
Now the mapping is the smallest problem, as well as the frame skipping (just access tb_next a couple of times). The real problems is reraising the exception in a different line and patching that new traceback into the traceback chain. There are solutions but it requires a C extension module and some code that you better hide. Still, it works :D
If you want to see how it’s implemented check those files:
So yes. You can patch tracebacks and customize them, but it’s deeper magic.
[…] as response to this I hacked up a “tbtools” module that contains various traceback helper functions to modify tracebacks. You can find it here: tbtools. […]
Comment by Lucumr Cogitations » Blog Archive » Patching Python Tracebacks -- Part Two — Saturday, June 16th, 2007 @ 11:54 am