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
# -*- 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':
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
print 'Variables at this point:'
sys._old_excepthook(exc_type, exception, traceback)
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