28 | 如何合理利用assert?

1.什么是assert?

在python中assert是debug的一个好工具,主要用于测试一个条件是否满足,如果满足则什么也不做,相当于执行了pass语句,如果测试条件不满足,便会抛出异常AssertionError,并返回具体的错误信息。

具体用法:

assert_stmt ::=  "assert" expression ["," expression]

简单形式assert expression,例如下面:

assert_stmt ::=  "assert" expression ["," expression]

相当于:

if __debug__:
    if not expression: raise AssertionError

再看下,assert expression1,expression2如下面的例子:

assert 1 == 2,  'assertion is wrong'

相当于这两行代码:

if __debug__:
    if not expression1: raise AssertionError(expression2)

2.assert的用法?

eg1:

def apply_discount(price, discount):
    updated_price = price * (1 - discount)
    assert 0 <= updated_price <= price, 'price should be greater or equal to 0 and less or equal to original price'
    return updated_price

验证:

apply_discount(100, 0.2)
80.0

apply_discount(100, 2)
AssertionError: price should be greater or equal to 0 and less or equal to original price

assert可以有效的预防bug发生,提高程序的健壮性。

eg2:

def func(input):
    assert isinstance(input, list), 'input must be type of list'
    # 下面的操作都是基于前提:input 必须是 list
    if len(input) == 1:
        ...
    elif len(input) == 2:
        ...
    else:
        ... 

这个函数func()里的所有操作,都是基于输入必须是list这个前提,必要在开头加一句assert检查,防止程序出错。

3.assert错误示例

def delete_course(user, course_id):
    assert user_is_admin(user), 'user must be admin'
    assert course_exist(course_id), 'course id must exist'
    delete(course_id)

eg1:

def delete_course(user, course_id):
    if not user_is_admin(user):
        raise Exception('user must be admin')
    if not course_exist(course_id):
        raise Exception('coursde id must exist')
    delete(course_id)  
def read_and_process(path):
    assert file_exist(path), 'file must exist'
    with open(path) as f:
      ...
def read_and_process(path):
    assert file_exist(path), 'file must exist'
    with open(path) as f:
      ...

猜你喜欢

转载自blog.csdn.net/yanyiting666/article/details/97621518
28
28-