python assert函数解析
python assert的作用:
assert函数用于程序调试
Python 官方文档解释https://docs.python.org/3/reference/simple_stmts.html#assert
“Assert statements are a convenient way to insert debugging assertions into a program”
assert断言语句是将调试断言插入程序的一种方便方法。
使用assert断言语句是一个非常好的习惯,python assert断言句语格式及用法很简单。在没完善一个程序之前,我们不知道程序在哪里会出错,与其让它在运行到最后崩溃,不如在出现错误条件时就崩溃,这样在跑大规模程序的时候不会过多的浪费时间和计算资源,这时候就需要assert断言的帮助。
1、The simple form:
assert expression
该形式用来测试断言的expression语句,如果expression是True,那么什么反应都没有。但是如果expression是False,那么会报错AssertionError,
例子:
assert 1==0
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-4-b09d6b060198> in <module>() ----> 1 assert 1==0, AssertionError:
不出错时,什么反应都没有:
assert 1==1
2、The extended form:
assert expression1, expression2
assert断言语句可以添加异常参数,也就是在断言表达式后添加字符串信息,用来解释断言并更好的知道是哪里出了问题。格式如下:
assert expression [, arguments] assert 表达式 [, 参数]
例子:
assert 1==0, "出错了"
-------------------------------------------------------< 24000 /span>-------------------- AssertionError Traceback (most recent call last) <ipython-input-4-b09d6b060198> in <module>() ----> 1 assert 1==0, "出错了" AssertionError: 出错了
不出错时,依旧什么反应都没有:
assert 1==1, "出错了"
3、The Equivalent expression:
The simple form, 断言assert expression, 等价于:
if __debug__: if not expression: raise AssertionError
官方文档中给出了下面一段话作为理解:
These equivalences assume that debug and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable debug is True under normal circumstances, False when optimization is requested (command line option -O). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.
Assignments to debug are illegal. The value for the built-in variable is determined when the interpreter starts.
这种“等价”假设了__debug__和AssertionError引用了具有这些名称的内置变量。在当前实现中,内置变量__debug__在正常情况下为True,在请求优化时为False(命令行选项-O)。当编译时请求优化时(内置变量__debug__为False),当前代码生成器不会为assert语句发出代码。注意,没有必要在错误消息中包含失败表达式的源代码;它将作为堆栈跟踪的一部分显示。
赋值给_debug__是非法的。内置变量的值在解释器启动时就是确定的。
(以上是个人的蹩脚翻译,欢迎指正)
- python-Levenshtein几个计算字串相似度的函数解析
- Python - 静态函数(staticmethod), 类函数(classmethod), 成员函数 区别(完全解析)
- Python中functools模块的常用函数解析
- 深入解析Python中函数的参数与作用域
- python的super函数解析
- Python最全内置函数合集!你应该没有见过这么全的函数以及解析
- python中threading的高级函数应用解析 Lock Rlock Condition Semaphore Timer Event Semaphore对象
- python assert 断言函数
- Python中functools模块的常用函数解析
- Python urllib的urlretrieve()函数解析 (显示下载进度)
- Python内建函数str,repr解析
- python-Levenshtein几个计算字串相似度的函数解析
- 深入解析Python中函数的参数与作用域
- 解析Python中的eval()、exec()及其相关函数
- python迭代和解析(3):range、map、zip、filter和reduce函数
- 洗礼灵魂,修炼python(25)--自定义函数(6)—从匿名函数进阶话题讲解中解析“函数式编程”
- python的函数对参数解析分析
- python的命令解析getopt.getopt()函数分析
- python命令行解析之parse_known_args()函数和parse_args()
- python中set()函数简介及实例解析