断言(assert)在很多语言中都存在,它主要为调试程序服务。 断言能够快速方便地检査程序的异常或者发现不恰当的输入等,可防止意想不到的情况出现。
Python自1.5版本开始引入断言语句,其基本语法如下:
assert expression1 ["," expression2]
x =1
y =2
assert x == y
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[2], line 3 1 x =1 2 y =2 ----> 3 assert x == y AssertionError:
assert x == y, '并不相等'
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[3], line 1 ----> 1 assert x == y, '并不相等' AssertionError: 并不相等
在执行过程中它实际相当于如下代码:
x =1
y =2
if __debug__ and not x == y:
raise AssertionError("并不相等")
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[4], line 4 2 y =2 3 if __debug__ and not x == y: ----> 4 raise AssertionError("并不相等") AssertionError: 并不相等
对Python中使用断言需要说明如下:
__debug__
的值默认设置为True
, 且是只读的。 在Python2.7中还无法修改该值。断言是有代价的,它会对性能产生一定的影响,对于编译型的语言,如C/C++,这也许并不那么重要,因为断言只在调试模式下启用 。 但Python并没有严格定义调试和发布模式之间的区別,通常禁用断言的方法是在运行脚本的时候加上
-O
标志, 这种方式带来的影响是它并不优化字节码,而是忽略与断言相关的语句。如:
def foo(x):
assert x
foo(0)
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[5], line 3 1 def foo(x): 2 assert x ----> 3 foo(0) Cell In[5], line 2, in foo(x) 1 def foo(x): ----> 2 assert x AssertionError:
运行 python asserttest.py
如下:
!python3 asserttest.py
python3: can't open file '/home/jovyan/work/jupylab_xuzp/pt03_thinking/ch11_调试/asserttest.py': [Errno 2] No such file or directory
加上 -O
的参数: python -O asserttest.py
便可以禁用断言。
!python3 -O asserttest.py
python3: can't open file '/home/jovyan/work/jupylab_xuzp/pt03_thinking/ch11_调试/asserttest.py': [Errno 2] No such file or directory
def stradd(x, y):
assert isinstance(x,basestring)
assert isinstance(y,basestring)
return x+y
不要使用断言来检査用户的输入。
如对于一个数字类型,如果根据用户的设计该值的范围应该是2 ~ 10, 较好的做法是使用条件判断,并在不符合条件的时候输出错误提示信息。
在函数调用后,当需要确认返回值是否合理时可以使用断言。
当条件是业务逻辑继续下去的先决条件时可以使用断言。
如
list1
和其副本list2
, 业务继续下去的条件是这两个list
必须是一样的。 但由于某些不可控因素,如使用了浅拷贝而list1
中含有可变对象等,就可以使用断言来判断这两者的关系, 如果不相等,则继续运行后面的程序意义不大。