什么是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 在程序中的作用,是对代码做一些 internal 的 self-check。使用 assert,就表示你很确定。这个条件一定会发生或者一定不会发生。
  注意:不能在使用assert时加上括号
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 的用法

  举例几个常用的场景。
  1.商品打折。要求输入为原来的价格和折扣,输出是折后的价格   
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的更多相关文章

  1. python 规范篇 如何合理使用 assert

    assert 的合理使用,可以增加代码的健壮度,同时也方便了程序出错时开发人员的定位排查. 什么是 assert? Python 的 assert 语句,可以说是一个 debug 的好工具,主要用于测 ...

  2. python raise和assert的区别

    python中raise和assert的区别 一.使用raise抛出异常 python可以自动触发异常,raise(内置函数)的定义为显示的抛出异常,用户可以使用raise进行判断,显式的引发异常,r ...

  3. PEP8 python规范神器

    如需转载,请注明出处:小婷儿的博客:https://www.cnblogs.com/xxtalhr/p/10645992.html 一.Jupyter notebook 篇 Jupyter noteb ...

  4. python 规范

    摘自google. https://i.cnblogs.com/PostDone.aspx?postid=9753605&actiontip=%E4%BF%9D%E5%AD%98%E4%BF% ...

  5. PYTHON 异常处理 一 ASSERT

    assert语句,如果没记错,这个东西在C或者C++里面也有的.属于短小的断言.下面的是来自python help document的说明: Assert statements are a conve ...

  6. Google实践中总结的Python规范,get了吗?

    好的代码风格,给人舒服的感觉,今天介绍一下谷歌的Python风格规范 1 分号 不要在行尾加分号, 也不要用分号将两条命令放在同一行. 2 行长度 每行不超过80个字符:不要使用反斜杠连接行.Pyth ...

  7. Python规范:提高可读性

    PEP 8 规范 PEP 是 Python Enhancement Proposal 的缩写,翻译过来叫"Python 增强规范". 缩进规范 PEP 8 规范告诉我们,请选择四个 ...

  8. Python规范:代码规范要注意

    主要有以下两种代码规范 <8 号 Python 增强规范>(Python Enhacement Proposal #8),以下简称 PEP8: <Google Python 风格规范 ...

  9. 基础python规范

    一.注释     合理的代码注释应该占源代码的 1/3 左右,Python 语言允许在任何地方插入空字符或注释,但不能插入到标识符和字符串中间.     在 Python 中,通常包括 3 种类型的注 ...

随机推荐

  1. SpringBoot终章(整合小型进销系统)

    在前面的章节中我们学习Spring的时候可以看到配置文件比较多,所以我们有了SpringBoot 1. 引入依赖 <dependencies> <dependency> < ...

  2. POJ 1741.Tree and 洛谷 P4178 Tree-树分治(点分治,容斥版) +二分 模板题-区间点对最短距离<=K的点对数量

    POJ 1741. Tree Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 34141   Accepted: 11420 ...

  3. @Aspect注解并不属于@Component的一种

    也就是一个类单纯如果只添加了@Aspect注解,那么它并不能被context:component-scan标签扫描到. 想要被扫描到的话,需要追加一个@Component注解

  4. SpringDataRedis的简单案例使用

    一.SpringDataRedis环境搭建 第一步.导入坐标 <!-- 缓存 --> <dependency> <groupId>redis.clients< ...

  5. element ui,input框输入时enter健进行搜索

    <el-form-item label="企业名称"> <el-input v-model="formSearch.kw" @keyup.en ...

  6. OpenFOAM——圆腔顶盖旋转驱流

    本算例来自<ANSYS Fluid Dynamics Verification Manual>中的VMFL008: Flow Inside a Rotating Cavity 腔体顶盖以1 ...

  7. windows 共享文件夹

    windows 共享文件夹 同步工作组 右键单击"计算机",选择"属性" 更改设置 单击"更改". 输入工作组 和 主机名 启计算机使更改生 ...

  8. css3学习之--transition属性(过渡)

    一.理解transition属性 W3C标准中对CSS3的transition是这样描述的: CSS的transition允许CSS的属性值在一定的时间区间内平滑地过渡.这种效果可以在鼠标单击,获得焦 ...

  9. 第06组 Beta冲刺(2/5)

    队名:拾光组 组长博客链接 作业博客链接 团队项目情况 燃尽图(组内共享) 组长:宋奕 过去两天完成了哪些任务 维护后端代码 学习后端架构 GitHub签入记录 接下来的计划 维护后端代码,跟进组员完 ...

  10. 【Qt开发】vs2017+qt5.x编译32位应用

    概述 最近有同学私信我,问如何使用vs2017+qt5.10编译出32位的应用,需要使用msvc2017_x86的插件,然而qt官网并没有提供,只能使用源码编译生成msvc2017_x86插件,使用n ...