Python中处理NumPy测试中的异常断言

2024-05-20 09:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

了解某人的代码并遇到以下情况:

有一个函数:

 def some_func():
       print("Hello")
       assert(len(y)==len(p))
       print("First assert")
       assert(p.all()<=0.99999)
       print("Second assert")
       return 1

接下来,调用断言引发:

np.testing.assert_raises(AssertionError, some_func, np.asarray([1, 2, 3]), np.asarray([1, 2, 3, 4, 5]))

在输出中,我们只得到Hello,没有异常消息:

Hello

接下来,调用函数assert\u array\u less:

np.testing.assert_array_less(some_func(np.asarray([1, 2, 3]), np.asarray([1, 2, 3])), np.inf)

在输出中,我们首先得到Hello assert,然后是错误消息和AssertionError异常:

Hello
First assert
---------------------------------------------------------------------------
AssertionError  Traceback (most recent call last)
<ipython-input-26-df1a32b4f5a0> in <module>()
      9 np.testing.assert_raises(AssertionError, some_func, np.asarray([1, 2, 3]), np.asarray([1, 2, 3, 4, 5]))
     10 
---> 11 np.testing.assert_array_less(some_func(np.asarray([1, 2, 3]), np.asarray([1, 2, 3])), np.inf)

<ipython-input-26-df1a32b4f5a0> in some_func(a, b)
      3     assert(len(a)==len(b))
      4     print("First assert")
----> 5     assert(a.all()<=0.99999)
      6     print("Second assert")
      7     return 1

AssertionError: 

问题:

为什么在1种情况下,虽然在某些函数()中调用了first assert,但代码只是停止,没有抛出异常?

为什么第二种情况与第一种情况不一样,并引发异常?


Tags: 代码hellolennp情况someasserttesting
1条回答
网友
1楼 · 发布于 2024-05-20 09:31:59

根据您显示的错误消息,我猜some_func函数的实际定义是:

def some_func(a, b):
    print("Hello")
    assert(len(a)==len(b))
    print("First assert")
    assert(a.all()<=0.99999)
    print("Second assert")
    return 1

有鉴于此,下面是您assert通话过程中发生的具体情况:

  • 你打电话来

    np.testing.assert_raises(AssertionError, some_func, np.asarray([1, 2, 3]), np.asarray([1, 2, 3, 4, 5]))
    
    • np.testing.assert_raises函数依次调用

      some_func(np.asarray([1, 2, 3]), np.asarray([1, 2, 3, 4, 5]))
      
      • 第一行some_func运行并打印Hello。你知道吗
      • 接下来,some_func尝试断言ab的长度是相同的。但是,a的长度是3,b的长度是5,因此断言失败。这会导致抛出AssertionError。此时,some_func的执行终止,控制返回到assert_raises。你知道吗
    • assert_raises通过传递给它的第一个参数被告知期望一个AssertionError。它看到一个AssertionError确实被抛出了,所以从它的角度来看一切都很好。它处理AssertionError(防止它创建一个错误消息显示给用户),并且assert_raises的执行正常结束。你知道吗
  • 下次你打电话来

    np.testing.assert_array_less(some_func(np.asarray([1, 2, 3]), np.asarray([1, 2, 3])), np.inf)
    
    • 再次,第一行some_func运行并打印Hello。你知道吗
    • 这一次,len(a)==len(b)==3,因此assert通过,some_func的执行正常继续。你知道吗
    • 接下来第三行some_func运行并打印First assert。你知道吗
    • a中的每个值都是非零的,因此a.all()True。布尔值True的数值为1。因此,a.all()<=0.99999False,因此assert失败。此时,将引发AssertionError,并终止some_func的执行。你知道吗
  • 这一次,some_func在顶级作用域中运行(如果它成功完成,np.testing.assert_array_less将被调用,some_func的返回值将被传递给它)。与上次调用some_func不同的是,没有封闭函数来处理引发的AssertionError。这意味着AssertionError将传播并生成在First assert下面打印出来的可见错误消息。你知道吗

事情就是这样。你知道吗

相关问题 更多 >