28 | 如何合理利用assert?

本文详细介绍了Python中assert语句的使用方法,包括其基本语法、如何用于调试和预防bug,以及通过具体示例展示了assert在函数参数校验和状态检查中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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:
      ...

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值