Python技巧--02(assert断言)
断言是什么
Python assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。
运用断言
example1(商店打折):
def apply_discount(product, discount):
price = int(product['price'] * (1.0 - discount))
assert 0 <= price <= product['price']
print(price)
shoes = {'name': 'nike', 'price': 1499}
apply_discount(shoes,0.25)
=> 1124
apply_discount(shoes,2)
=> Traceback (most recent call last):
File "/Users/sangyuming/Desktop/test.py", line 20, in <module>
apply_discount(shoes, 2.5)
File "/Users/sangyuming/Desktop/test.py", line 13, in apply_discount
assert 0 <= price <= product['price']
AssertionError
example2(判断类型):
type_str = 'asdfasdf'
assert type(type_str) == str
=>
assert type(type_str) == int
=>
Traceback (most recent call last):
File "/Users/sangyuming/Desktop/test.py", line 24, in <module>
assert type(type_str) == int
AssertionError
断言语法
assert [表达式]
等价于:
if not [表达式]:
raise AssertionError
由此可知,[表达式] 实际是if的判断语句
使用场景
- 在代码测试时使用
- 对代码单元逻辑的检测
- 对于复杂程序的类型、常量、条件的检测
😈使用陷阱
- 使用断言会给程序带来安全风险和bug,因此实际生产环境中不要使用或设置关闭断言
- 形成怪癖,会编写许多无用的断言
注意事项
1. 不要使用断言验证数据
因为断言是可以全局关闭的,所以如果断言用在权限验证上,则会造成严重的后果

浙公网安备 33010602011771号