6.13 global语句 The global statement

global_stmt  ::=  "global" identifier ("," identifier)*
Download entire grammar as text.

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

global语句是对整个代码块都有作用的一个声明. 它指出其所列的标识符要解释为全局的.如果某名字在局部名字空间中没有定义, 就自动使用相应的全局名字. 没有global是不可能手动指定一个名字是全局的.

Names listed in a global statement must not be used in the same code block textually preceding that global statement.

在 global 中出现的名字不能在global 之前的代码中使用.

Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.

在 global 中出现的名字不能作为形参, 不能作为循环的控制对象, 不能在类定义, 函数定义, import语句中出现.

(The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.)

(当前实现不强制执行后两种限制, 但程序不能滥用这种自由, 以后的实现可能会对其强行限制或者可能会改变程序行为而没有任何提示.)

Programmer's note: the global is a directive to the parser. It applies only to code parsed at the same time as the global statement. In particular, a global statement contained in an exec statement does not affect the code block containing the exec statement, and code contained in an exec statement is unaffected by global statements in the code containing the exec statement. The same applies to the eval(), execfile() and compile() functions.

程序员注意: global是一个解析器的指示字. 它仅仅会对和global一起解析的代码有效.特别地, exec语句中的global语句不会对包括有该exec语句的代码块产生影响. 并且exec语句中的global语句也不对exec语句中的代码产生影响. 相同的机制也应用于eval(), execfile() 和 compile() 函数.