如何自动生成断言信息?

时间:2019-01-31 22:21:42

标签: python python-3.x assertion

在python中,每当我使用断言并被触发时,我只会得到一个丑陋的信息:

AssertionError

我应该怎么做才能通过解析条件参数的AST自动生成一条解释错误原因的消息?

例如:所以

assert 2 == 3

原因:

AssertionError: 2 != 3

3 个答案:

答案 0 :(得分:0)

如果依赖项是一个问题,您可以自己轻松完成。即:

def assert_eq(x, y):
  if x != y:
    print('error: {} != {}'.format(x, y))
  assert x == y

答案 1 :(得分:0)

实现目标的一种简单方法是使用包装函数,该函数将已声明的条件作为字符串参数,以便可以evalassert捕获{ AssertionError中的{1}},以便您可以使用给定的字符串作为消息重新引发异常:

try

这样:

def my_assert(condition):
    try:
        assert eval(condition)
    except AssertionError as e:
        e.args = condition,
        raise

会加薪:

my_assert('2 == 3')

答案 2 :(得分:0)

由于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