Python Assert断言

Assert断言声明

Assert断言可以很方便的在调试程序时插入调式断言。

基本语法:assert expression等价于

if __debug__:
    if not expression: raise AssertionError

扩展语法:assert expression1, expression2等价于

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

这些等价假定__debug__AssertionError引用带有这些名称的内置变量。 在当前实现中,正常情况下内置变量__debug__True
,请求优化时为False(命令行选项-O)。 当编译时请求优化时,当前的代码生成器不会为assert语句发出代码。 请注意,不必在错误消息中包含失败表达式的源代码; 它将显示为堆栈跟踪的一部分。

__debug__的赋值是非法的。 内置变量的值在解释器启动时确定。

猜你喜欢

转载自blog.csdn.net/u014108439/article/details/79820907