Skip to content

Instantly share code, notes, and snippets.

@flying-sheep
Forked from martinth/assertion_hook.py
Created August 8, 2011 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flying-sheep/1132816 to your computer and use it in GitHub Desktop.
Save flying-sheep/1132816 to your computer and use it in GitHub Desktop.
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]
print(statement)
# 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:")
pprint.pprint(names_and_vars)
else:
# 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)
print(j)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment