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 种类型的注 ...
随机推荐
- java 数组遍历(方法内部的代码)
//数组遍历(依次输出数组中的每一个元素)二维数组: int[][] arr={{1,2},{3,4,5},{6,7}}; for(int i=0;i<arr.length;i++){ for( ...
- vue 首页导航+左侧菜单
1. Mock.js 前后端分离开发开发过程当中,经常会遇到以下几个尴尬的场景: 1. 老大,接口文档还没输出,我的好多活干不下去啊! 2. 后端小哥,接口写好了没,我要测试啊! 前后端分离之后,前端 ...
- Kafka(四) —— KafkaProducer源码阅读
一.doSend()方法 Kafka中的每一条消息都对应一个ProducerRecord对象. public class ProducerRecord<K, V> { private fi ...
- ArgumentException: The Assembly Mono.WebBrowser is referenced by System.Windows.Forms ('Assets/Plugins/System.Windows.Forms.dll'). But the dll is not allowed to be included or could not be found.
最近有个项目要用到System.Windows.Forms.dll,在Unity编辑器里用着还好好的,但是一导出就给我报错,让我十分不爽. 于是请教百度,搜出了五花八门的答案,没一个能解决我的问题的, ...
- IDEA将指定package(指定文件)打成jar包
写在前面 真的是好记性不如烂笔头 需求 将项目中包名为org的package打成jar包 步骤 1.选择Artifacts>绿色+号>JAR>Empty name自定义, 我这里命名 ...
- Intellij idea 告警:URI is not registered (Settings | Languages & Frameworks | Schemas and DTDs)
URI is not registered (Settings | Languages & Frameworks | Schemas and DTDs) 一.快捷键方式 鼠标移动到出错的的地方 ...
- EF6中的SQL监控
在MVC或WEBAPI中的监控 System.Action<string> action = (string message) => { Debug.WriteLine(messag ...
- VBA 如何检测一个中文字符串是否包含在另一个字符串中
Sub test() aaa = "江苏省南京市建邺区水西门大街34号" If InStr(aaa, Then MsgBox "在里面" Else MsgBox ...
- 学习使用Lombok生成代码
一.介绍 Lombok官网:https://projectlombok.org/ Lombok的功能简单一点说,就是可以帮我们生成一些代码,这些代码并不是在源码(source code)体现出来的,而 ...
- js 模糊搜索
function fuzzysearch (needle, haystack) { var hlen = haystack.length; var nlen = needle.length; if ( ...