python 的 assert 语句

本文详细介绍了Python中assert语句的用法,包括其作为条件判断和错误处理的特性,展示了如何在输入验证、代码检查、环境依赖和错误预防中应用assert,强调了合理使用assert对提高代码质量的重要性。
摘要由CSDN通过智能技术生成

简介


python 的 assert 语句,用于测试一个条件是否满足.如果条件满足,就pass ,如果条件不满足就会返回 AssertionError,与具体相关错误.简单例子


assert 1==2
# 相当与
if __debug__:
    if not 1==2:raise AssertionError

assert 1 == 2,'assertion is wrong'
# 相当与
if __debug__:
    if not 1==2:raise AssertionError('assertion is wrong')

阻止执行


>> Python assert.py -O   
#参数 -0 可以不执行程序的所有 assert

具体实例



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

# 2.检查代码
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(80,0.1)
apply_discount(80,2)
# AssertionError: price should be greater or equal to 0 and less or equal to original price



# 3.判断环境
# import sys
assert ('linux' in sys.platform), "该代码只能在 Linux 下执行"

不能滥用



# 4.我们也不能滥用 assert。
# 比如想打开文件,进行数据读取,用assert 判断文件是否存在,是不对的
# 因为 assert 是可以不被执行的,所以必须加上强有力的条件 用 if  或者 try except
def read_and_process(path):
    assert file_exist(path), 'file must exist'
    with open(path) as f:
      ...


def read_and_process(path):
    try:
        with open(path) as f:
            ...
    except Exception as e:
            ...

总结

# assert 语句是可以有效预防 bug 的发生,增强代码的健壮性,如果不满足预设条件就报错
# assert的使用应该是,有没有assert程序都能够正常运行,但有了assert可以使我们的代码后期维护更加方便
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值