Since AssertionError
is a class, you can derive your own that does what you want. The tricky part is hooking it up so the interpreter will use it with assert
statment.
Here's something that seems to work, but I don't know whether that will be the case when used in conjunction with jupyter notebook.
import builtins
import traceback
class MyAssertionError(builtins.AssertionError):
def __init__(self, *args):
super(MyAssertionError, self).__init__(*args)
raw_tb = traceback.extract_stack()
entries = traceback.format_list(raw_tb)
# Remove the last two entries for the call to extract_stack(). Each
# entry consists of single string with consisting of two lines, the
# script file path then the line of source code making the call to this
# function.
del entries[-2:]
self.lines = '\n'.join(entries)
def __str__(self):
return super(MyAssertionError, self).__str__() + '\n' + self.lines
builtins.AssertionError = MyAssertionError # Replace builtin.
if __name__ == '__main__':
assert 2 == 3