Поскольку AssertionError
- это класс, вы можете получить свой собственный, который делает то, что вы хотите.Сложная задача - подключить его, чтобы интерпретатор использовал его с assert
комментарием.
Вот кое-что, что, кажется, работает, но я не знаю, будет ли это так при использовании в сочетании с ноутбуком Jupyter.
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