python中assert的使用

python 中assert断言是声明其布尔值必须为真的判定,如果发生异常就说明表达式为假。可以理解assert断言语句为raise-if-not,用来测试表示式,其返回值为假,就会触发异常。

Python的assert是用来检查一个条件,如果它为真,就不做任何事。如果它为假,则会抛出AssertError并且包含错误信息。

assert的异常参数,其实就是在断言表达式后添加字符串信息,用来解释断言并更好的知道是哪里出了问题。格式如下:
assert expression [, arguments]
即:assert 表达式 [, 参数]

一般的用法是:

assert condition

用来让程序测试这个condition,如果condition为false,那么raise一个AssertionError出来。逻辑上等同于:

if not condition:
    raise AssertionError()

抛出异常是为了可以及时查找到错误信息,避免把错误信息在程序中继续运行。

什么时候应该使用assert?没有特定的规则,断言应该用于:

防御型的编程
测试代码
运行时检查程序逻辑
检查约定
程序常量
检查文档

python doc中这么解释:
(https://docs.python.org/3/reference/simple_stmts.html#assert)

Assert statements are a convenient way to insert debugging assertions into a program:

assert_stmt ::=  "assert" expression ["," expression]

The simple form, assert expression, is equivalent to

if __debug__:
    if not expression: raise AssertionError

The extended form, assert expression1, expression2, is equivalent to

if __debug__:
    if not expression1: raise AssertionError(expression2)

参考:http://blog.jobbole.com/76285/

你可能感兴趣的:(python基础学习,python,异常,断言,assert)