assert(断言):

assert condition

assert 可以作为判断,在结果为True时什么都不返回,在结果为False时会触发一个错误,它等价于下面的判断

if not condition:
    raise AssertionError()

测试下:

\>>> assert True # nothing happens
assert False
Traceback (most recent call last):
File "", line 1, in
AssertionError
\>>>

assert还可以包含一个额外的错误消息选项,如下面

\>\>\> assert False, '这是一个错误'
Traceback (most recent call last):
File "", line 1, in
AssertionError: 这是一个错误
\>>>
\>>> assert 1==2,('%s, 1不等于%d' % ('hello', 2))
Traceback (most recent call last):
File "", line 1, in
AssertionError: hello, 1不等于2
\>>>