Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A sample exception hook, that prints useful information if an AssertionError occures
#!/usr/bin/env python3
import sys, pprint
import os.path
# save old exception hook
sys._old_excepthook = sys.excepthook
def assert_hook(exc_type, exception, traceback):
if exc_type.__name__ == "AssertionError":
# get info from traceback
frame = traceback.tb_frame
local = frame.f_locals
line = frame.f_lineno
codefile = frame.f_code.co_filename
print("Assertion error in file '{}' at line {}:\n".format(codefile, line))
with open(codefile) as f:
# get statement at the line from the stacktrace and print it
statement = f.readlines()[line-1]
# compile the statement in that line, get all variables from the compiled
# code, put the variables from that line in a dict with the values from the
# traceback and dump everything
code = compile(statement.strip(), codefile, "single")
names_at_line = filter(lambda name: name != "AssertionError", code.co_names)
names_and_vars = dict( (name, local[name]) for name in names_at_line )
print("Variables at this point:")
# all non AssertionError exception get handled
sys._old_excepthook(exc_type, exception, traceback)
sys.excepthook = assert_hook
if __name__ == "__main__":
i = 5
for j in range(10):
assert(j < i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment