Python规范:用用assert
什么是assert
assert的语法:
assert_stmt ::= "assert" expression ["," expression]
例:
assert 1 == 2, 'assertion is wrong'
Traceback (most recent call last):
File "assert.py", line 4, in <module>
assert 1 == 2, 'assertion is wrong'
AssertionError: assertion is wrong
相当于
if __debug__:
if not expression1: raise AssertionError(expression2)
assert(1 == 2, 'This should fail')
# 输出
<ipython-input-8-2c057bd7fe24>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert(1 == 2, 'This should fail')
assert 的用法
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
如果assert的条件为False,会raise
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
2.后台想知道每个商品的平均销售价格,算法是销售总额 / 销售数目:
def calculate_average_price(total_sales, num_sales):
assert num_sales > 0, 'number of sales should be greater than 0'
return total_sales / num_sales
加入了 assert 语句,规定销售数目必须大于 0.
3.检查输入是否list
def func(input):
assert isinstance(input, list), 'input must be type of list'
# 下面的操作都是基于前提:input 必须是 list
if len(input) == 1:
...
elif len(input) == 2:
...
else:
...
assert 错误示例
assert 的检查是可以被关闭的,比如在运行 Python 程序时,加入-O这个选项就会让 assert 失效。因此,一旦 assert 的检查被关闭,user_is_admin() 和 course_exist() 这两个函数便不会被执行。这就会导致严重问题:
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)
对于程序中的一些 run-time error,还是得用异常处理
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)
参考
极客时间《Python核心技术与实战》专栏
Python规范:用用assert的更多相关文章
- python 规范篇 如何合理使用 assert
assert 的合理使用,可以增加代码的健壮度,同时也方便了程序出错时开发人员的定位排查. 什么是 assert? Python 的 assert 语句,可以说是一个 debug 的好工具,主要用于测 ...
- python raise和assert的区别
python中raise和assert的区别 一.使用raise抛出异常 python可以自动触发异常,raise(内置函数)的定义为显示的抛出异常,用户可以使用raise进行判断,显式的引发异常,r ...
- PEP8 python规范神器
如需转载,请注明出处:小婷儿的博客:https://www.cnblogs.com/xxtalhr/p/10645992.html 一.Jupyter notebook 篇 Jupyter noteb ...
- python 规范
摘自google. https://i.cnblogs.com/PostDone.aspx?postid=9753605&actiontip=%E4%BF%9D%E5%AD%98%E4%BF% ...
- PYTHON 异常处理 一 ASSERT
assert语句,如果没记错,这个东西在C或者C++里面也有的.属于短小的断言.下面的是来自python help document的说明: Assert statements are a conve ...
- Google实践中总结的Python规范,get了吗?
好的代码风格,给人舒服的感觉,今天介绍一下谷歌的Python风格规范 1 分号 不要在行尾加分号, 也不要用分号将两条命令放在同一行. 2 行长度 每行不超过80个字符:不要使用反斜杠连接行.Pyth ...
- Python规范:提高可读性
PEP 8 规范 PEP 是 Python Enhancement Proposal 的缩写,翻译过来叫"Python 增强规范". 缩进规范 PEP 8 规范告诉我们,请选择四个 ...
- Python规范:代码规范要注意
主要有以下两种代码规范 <8 号 Python 增强规范>(Python Enhacement Proposal #8),以下简称 PEP8: <Google Python 风格规范 ...
- 基础python规范
一.注释 合理的代码注释应该占源代码的 1/3 左右,Python 语言允许在任何地方插入空字符或注释,但不能插入到标识符和字符串中间. 在 Python 中,通常包括 3 种类型的注 ...
随机推荐
- shell脚本awk的基本用法
AWK 1 AWK 2 3 linux取IP地址 4 5 ifconfig | grep -w inet | sed -n '1p' | awk '{print $2}' 6 7 eg: 8 9 aw ...
- PHP.INI生成环境配置文件
extension_dir = /home/php/lib/php/extensions/no-debug-zts- zend_extension = opcache.so extension = p ...
- 解决js加减乘除精度问题
// 加法 const accAdd = (arg1, arg2) => { var r1, r2, m; try { r1 = arg1.toString(). ...
- Postgresql 数据库迁移步骤
1.操作位置:迁移数据库源(旧数据库主机) 找到PostgreSql 的data目录 关闭数据库进程 打包 tar -zcvf pgdatabak.tar.gz data/ ----------- ...
- [BUAA软工]团队任务拆解
团队任务分解 本次博客为项目alpha的任务拆解 WBS 任务估计 任务 时长(h) 语音模块:监听部分 5h 语音模块:消息处理:api 4h 语音模块:消息处理:内部数据结构 3h 语音模块:消息 ...
- [Beta]第二次 Scrum Meeting
[Beta]第二次 Scrum Meeting 写在前面 会议时间 会议时长 会议地点 2019/5/6 22:00 30min 大运村公寓6F楼道 附Github仓库:WEDO 例会照片 工作情况总 ...
- Server 2003 操作系统位数
安装好电脑系统,如何查看windows 2003/xp/win7是64位还是32位? 方法/步骤 第一种方法:桌面上鼠标右键单击“计算机”(我的电脑) 在弹出的快捷菜单中选择“属性”,如果看到64的字 ...
- sip user Authentication and 401
https://www.vocal.com/sip-2/sip-user-authentication/ https://tools.ietf.org/html/rfc3261 SIP User Au ...
- sklearn逻辑回归(Logistic Regression,LR)调参指南
python信用评分卡建模(附代码,博主录制) https://study.163.com/course/introduction.htm?courseId=1005214003&utm_ca ...
- Nginx location wildcard
Module ngx_http_core_modulehttps://nginx.org/en/docs/http/ngx_http_core_module.html#location locatio ...