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:
...
简介python 的 assert 语句,用于测试一个条件是否满足.如果条件满足,就pass ,如果条件不满足就会返回 AssertionError,与具体相关错误.简单例子assert 1==2# 相当与if __debug__: if not 1==2:raise AssertionErrorassert 1 == 2,'assertion is wrong'# 相当与if __debug__: if not 1==2:raise AssertionError(