assert是啥
python内置的断言语句(assert statement)。语法如下:
assert <condition>
assert <condition>,<error message>
当condition
为True时,顺序执行下一语句;当condition
为False时,程序会终止并抛出AssertionError
,如果assert语句有error message,则会在AssertionError
后显示该信息。
assert的使用场景
- 检查参数的类型和取值。
相比raise Error()
,代码更简洁 - debug
实例1
参数取值检查
import math
def sqrt(a):
assert a>=0, 'a must be a>=0'
return math.sqrt(a)
In [2]: sqrt(4)
Out[2]: 2.0
In [3]: sqrt(-4)
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-3-ee0bfbfc0490> in <module>
----> 1 sqrt(-4)
<ipython-input-1-6a938e83fb43> in sqrt(a)
1 import math
2 def sqrt(a):
----> 3 assert a>=0, 'a must be a>=0'
4 return math.sqrt(a)
5
AssertionError: a must be a>=0