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 种类型的注 ...
随机推荐
- create系列创建节点的方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Pivotal Greenplum 6.0 新特性介绍
Pivotal Greenplum 6.0 新特性介绍 在1月12日举办的Greenplum开源有道智数未来技术研讨会上,Pivotal中国研发中心Greenplum 产品经理李阳向大家介绍了Pi ...
- C++ 模板元编程 学习笔记
https://blog.csdn.net/K346K346/article/details/82748163 https://www.jianshu.com/p/b56d59f77d53 https ...
- 开源项目 05 Dapper
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- Beta冲刺(4/5)
队名:無駄無駄 组长博客 作业博客 组员情况 张越洋 过去两天完成了哪些任务 讨论校园百科究竟如何实现,并分配了任务 提交记录(全组共用) 接下来的计划 加快校园百科的进度 准备Beta版本的汇报 还 ...
- 帝国cms万能标签实现标题截取后自动加入省略号的方法
很多采用帝国CMS建站的站长都会遇到标题过长导致页面排版错乱的情况,这时候往往需要用标题截取并追加上省略号的方法予以解决.对此,帝国CMS万能标签标题截取后自动加入省略号,没有达到字数的则不加省略号可 ...
- Java中在时间戳计算的过程中遇到的数据溢出问题
背景 今天在跑定时任务的过程中,发现有一个任务在设置数据的查询时间范围异常,出现了开始时间戳比结束时间戳大的奇怪现象,计算时间戳的代码大致如下. package com.lingyejun.authe ...
- CSS各类布局
http://www.liquidapsive.com/ 1 静态布局(Static Layout)网页上的所有元素的尺寸一律使用px作为单位.特点:不管浏览器尺寸具体是多少,网页布局始终按照最初写代 ...
- Hadoop(四)—— MapReduce
一.Hadoop版本特性 MRv1 第一代计算框架,由编程模型和运行时环境两部分组成. 编程模型是,将数据进行map操作,然后进行reduce操作,最后将计算结果存储到HDFS中. 运行时环境是,由J ...
- LDD3源码分析之poll分析
编译环境:Ubuntu 10.10 内核版本:2.6.32-38-generic-pae LDD3源码路径:examples/scull/pipe.c examples/scull/main.c 本 ...