Created
August 8, 2011 21:24
-
-
Save martinth/1132789 to your computer and use it in GitHub Desktop.
A sample exception hook, that prints useful information if an AssertionError occures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
import sys | |
import os.path | |
import pprint | |
sys._old_excepthook = sys.excepthook | |
def assert_hook(exc_type, exception, traceback): | |
if exc_type.__name__ == 'AssertionError': | |
try: | |
frame = traceback.tb_frame | |
local = frame.f_locals | |
line = frame.f_lineno | |
codefile = frame.f_code.co_filename | |
print "Assertion error in file '%s' at line %d:\n"\ | |
% (codefile, line) | |
with open(codefile) as f: | |
statement = f.readlines()[line - 1] | |
print statement | |
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) | |
except: | |
sys._old_excepthook(exc_type, exception, traceback) | |
else: | |
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