6.2 断言语句 Assert statements

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

断言语句是一个在程序中插入调试断言的常用方法:

assert_stmt  ::=  "assert" expression ["," expression]
Download entire grammar as text.

The simple form, "assert expression", is equivalent to

简单形式的, "assert expression", 等价于:

if __debug__:
   if not expression: raise AssertionError

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

扩展形式的, "assert expression", 等价于:

if __debug__:
   if not expression1: raise AssertionError, expression2

These equivalences assume that __debug__and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is 1 under normal circumstances, 0 when optimization is requested (command line option -O). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.

这些等价式假定了存在 __debug__ 和 AssertionError , 而不是具有相同名字的相应内建变量.在当前实现, 内建变量__debug__在普通情况下为1, 在要求优化的情况下为0(命令行选项-O) 在编译要求优化时, 当前的代码生成器不产生任何断言语句的代码.注意在错误信息包括源代码的作法是多余的; 因为它们会作为跟踪回溯对象的一部分显示.

Assignments to __debug__ are illegal. The value for the built-in variable is determined when the interpreter starts.

给__debug__赋值是非法的,解释器是在启动时读取内建变量的值的.