Python assert 断言

来源:互联网 发布:qq微商软件 编辑:程序博客网 时间:2024/05/31 19:35

Python assert 断言

使用语法为:

assert expression [, arguments]

当expression为False时,触发异常,并返回arguments。在这里的arguments可以为字符串或者其他表达式等。


例1(无参数):

def test(a):    assert len(a)<10, a = [x for x in range(20)]test(a)

例1错误信息为:

Traceback (most recent call last):  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 5, in <module>    test(a)  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 2, in test    assert len(a)<10AssertionError

例2(参数为字符串):

def test(a):    assert len(a)<10, 'Input is too long'a = [x for x in range(20)]test(a)

例2错误信息为:

Traceback (most recent call last):  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 7, in <module>    test(a)  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 4, in test    assert len(a)<10, 'Input is too long'AssertionError: Input is too long

例3(参数为表达式):
个人想法:可以利用表达式这个特性,来动态地根据错误发生的实际情况来产生不同的错误信息,以便更好地来查找错误。

def test(a):    assert len(a)<10, 'The length of input is ' + str(len(a)) + ' , and we just need 10.'a = [x for x in range(20)]test(a)

例3错误信息为:

Traceback (most recent call last):  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 7, in <module>    test(a)  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 4, in test    assert len(a)<10, 'The length of input is ' + str(len(a)) + ' , and we just need 10.'AssertionError: The length of input is 20 , and we just need 10.

assert 和 if not … raise 实现相同功能:
例4:

def test(a):    if not len(a)<10:        raise ValueErrora = [x for x in range(20)]test(a)

例4错误信息:

Traceback (most recent call last):  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 8, in <module>    test(a)  File "/Users/lixiang/Desktop/ForJob/Py_assert.py", line 5, in test    raise ValueErrorValueError