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__
的赋值是非法的。 内置变量的值在解释器启动时确定。