4. Execution model执行模型¶
4.1. Structure of a program程序的结构¶
A Python program is constructed from code blocks. Python程序由代码块构造而成。A block is a piece of Python program text that is executed as a unit. 块是作为一个单元执行的一段Python程序文本。The following are blocks: a module, a function body, and a class definition. 以下是模块、函数体和类定义。Each command typed interactively is a block. 以交互方式键入的每个命令都是一个块。A script file (a file given as standard input to the interpreter or specified as a command line argument to the interpreter) is a code block. 脚本文件(作为解释器的标准输入或指定为解释器的命令行参数的文件)是代码块。A script command (a command specified on the interpreter command line with the 脚本命令(在解释器命令行上使用-c
option) is a code block. -c
选项指定的命令)是一个代码块。A module run as a top level script (as module 使用__main__
) from the command line using a -m
argument is also a code block. -m
参数从命令行以顶层脚本(作为模块__main__
)运行的模块也是一个代码块。The string argument passed to the built-in functions 传递给内置函数eval()
and exec()
is a code block.eval()
和exec()
的字符串参数是一个代码块。
A code block is executed in an execution frame. 代码块在执行帧中执行。A frame contains some administrative information (used for debugging) and determines where and how execution continues after the code block’s execution has completed.框架包含一些管理信息(用于调试),并确定代码块执行完成后在何处以及如何继续执行。
4.2. Naming and binding命名和绑定¶
4.2.1. Binding of names名称的绑定¶
Names refer to objects. 参考对象。Names are introduced by name binding operations.名称是通过名称绑定操作引入的。
The following constructs bind names:以下构造绑定名称:
formal parameters to functions,函数的形式参数,class definitions,类别定义,function definitions,函数定义,assignment expressions,赋值表达式,targets that are identifiers if occurring in an assignment:任务中出现的标识符目标:import
statements.语句。
The 表单的import
statement of the form from ... import *
binds all names defined in the imported module, except those beginning with an underscore. import
语句from ... import *
绑定导入模块中定义的所有名称,以下划线开头的名称除外。This form may only be used at the module level.此表格只能在模块级使用。
A target occurring in a del
statement is also considered bound for this purpose (though the actual semantics are to unbind the name).del
语句中出现的目标也被认为是为了这个目的而绑定的(尽管实际的语义是解除名称绑定)。
Each assignment or import statement occurs within a block defined by a class or function definition or at the module level (the top-level code block).每个赋值或导入语句都发生在由类或函数定义定义的块内,或者发生在模块级(顶层代码块)。
If a name is bound in a block, it is a local variable of that block, unless declared as 如果名称绑定在块中,则它是该块的局部变量,除非声明为nonlocal
or global
. nonlocal
或global
。If a name is bound at the module level, it is a global variable. 如果名称在模块级别绑定,则它是一个全局变量。(The variables of the module code block are local and global.) (模块代码块的变量为局部变量和全局变量。)If a variable is used in a code block but not defined there, it is a free variable.如果在代码块中使用了一个变量,但没有在代码块中定义,则它是一个自由变量。
Each occurrence of a name in the program text refers to the binding of that name established by the following name resolution rules.程序文本中出现的每个名称都是指由以下名称解析规则建立的该名称的绑定。
4.2.2. Resolution of names名称解析¶
A scope defines the visibility of a name within a block. 范围定义名称在块中的可见性。If a local variable is defined in a block, its scope includes that block. 如果在块中定义了局部变量,则其范围包括该块。If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name.如果定义出现在功能块中,则范围将扩展到定义块中包含的任何块,除非包含的块为名称引入不同的绑定。
When a name is used in a code block, it is resolved using the nearest enclosing scope. 在代码块中使用名称时,将使用最近的封闭范围来解析名称。The set of all such scopes visible to a code block is called the block’s environment.代码块可见的所有此类作用域的集合称为块的环境。
When a name is not found at all, a 如果根本找不到名称,将引发NameError
exception is raised. NameError
异常。If the current scope is a function scope, and the name refers to a local variable that has not yet been bound to a value at the point where the name is used, an 如果当前作用域是函数作用域,且名称引用的局部变量尚未绑定到使用该名称的点处的值,则会引发UnboundLocalError
exception is raised. UnboundLocalError
异常。UnboundLocalError
is a subclass of NameError
.UnboundLocalError
是NameError
的子类。
If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. 如果名称绑定操作发生在代码块内的任何位置,则块内名称的所有使用都将被视为对当前块的引用。This can lead to errors when a name is used within a block before it is bound. 如果在绑定块之前在块中使用名称,则可能会导致错误。This rule is subtle. 这条规则很微妙。Python lacks declarations and allows name binding operations to occur anywhere within a code block. Python缺少声明,允许名称绑定操作在代码块中的任何位置发生。The local variables of a code block can be determined by scanning the entire text of the block for name binding operations.通过扫描代码块的整个文本进行名称绑定操作,可以确定代码块的局部变量。
If the 如果global
statement occurs within a block, all uses of the names specified in the statement refer to the bindings of those names in the top-level namespace. global
语句出现在一个块中,则语句中指定的名称的所有用法都引用顶级命名空间中这些名称的绑定。Names are resolved in the top-level namespace by searching the global namespace, i.e. the namespace of the module containing the code block, and the builtins namespace, the namespace of the module 通过搜索全局名称空间(即包含代码块的模块名称空间)和内置名称空间(模块builtins
. builtins
名称空间),可以在顶级名称空间中解析名称。The global namespace is searched first. If the names are not found there, the builtins namespace is searched. 首先搜索全局命名空间。如果在那里找不到名称,则搜索内置名称空间。The global
statement must precede all uses of the listed names.global
语句必须位于所列名称的所有使用之前。
The global
statement has the same scope as a name binding operation in the same block. global
语句的作用域与同一块中的名称绑定操作的作用域相同。If the nearest enclosing scope for a free variable contains a global statement, the free variable is treated as a global.如果自由变量的最近封闭范围包含全局语句,则该自由变量将被视为全局变量。
The nonlocal
statement causes corresponding names to refer to previously bound variables in the nearest enclosing function scope. nonlocal
语句使相应的名称引用最近的封闭函数范围中以前绑定的变量。SyntaxError
is raised at compile time if the given name does not exist in any enclosing function scope.如果给定名称不存在于任何封闭函数作用域中,则在编译时引发。
The namespace for a module is automatically created the first time a module is imported. 模块的命名空间在第一次导入模块时自动创建。The main module for a script is always called 脚本的主模块始终称为__main__
.__main__
。
Class definition blocks and arguments to exec()
and eval()
are special in the context of name resolution. exec()
和eval()
的类定义块和参数在名称解析上下文中是特殊的。A class definition is an executable statement that may use and define names. 类定义是可以使用和定义名称的可执行语句。These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. 这些引用遵循名称解析的常规规则,但在全局名称空间中查找未绑定的局部变量除外。The namespace of the class definition becomes the attribute dictionary of the class. 类定义的命名空间成为类的属性字典。The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes comprehensions and generator expressions since they are implemented using a function scope. 类块中定义的名称范围仅限于类块;它不扩展到方法的代码块,这包括理解和生成器表达式,因为它们是使用函数作用域实现的。This means that the following will fail:这意味着以下操作将失败:
class A:
a = 42
b = list(a + i for i in range(10))
4.2.3. Builtins and restricted execution内置和限制执行¶
CPython implementation detail:CPython实施详情: Users should not touch 用户不得触摸__builtins__
; it is strictly an implementation detail. __builtins__
;这是一个严格的实施细节。Users wanting to override values in the builtins namespace should 想要覆盖内置名称空间中的值的用户应该导入import
the builtins
module and modify its attributes appropriately.builtins
模块并适当修改其属性。
The builtins namespace associated with the execution of a code block is actually found by looking up the name 与代码块的执行相关联的内置名称空间实际上是通过在其全局名称空间中查找名称__builtins__
in its global namespace; this should be a dictionary or a module (in the latter case the module’s dictionary is used). __builtins__
来找到的;这应该是一个字典或模块(在后一种情况下,使用模块的字典)。By default, when in the 默认情况下,在__main__
module, __builtins__
is the built-in module builtins
; when in any other module, __builtins__
is an alias for the dictionary of the builtins
module itself.__main__
模块中,__builtins__
是内置模块内置;在任何其他模块中,builtins
是builtins
模块本身字典的别名。
4.2.4. Interaction with dynamic features与动态特征的交互¶
Name resolution of free variables occurs at runtime, not at compile time. 自由变量的名称解析发生在运行时,而不是编译时。This means that the following code will print 42:这意味着将打印以下代码42:
i = 10
def f():
print(i)
i = 42
f()
The eval()
and exec()
functions do not have access to the full environment for resolving names. eval()
和exec()
函数无权访问用于解析名称的完整环境。Names may be resolved in the local and global namespaces of the caller. 可以在调用方的本地和全局名称空间中解析名称。Free variables are not resolved in the nearest enclosing namespace, but in the global namespace. 自由变量不会在最近的封闭命名空间中解析,而是在全局命名空间中解析。1 The exec()
and eval()
functions have optional arguments to override the global and local namespace. exec()
和eval()
函数有可选参数来覆盖全局和本地命名空间。If only one namespace is specified, it is used for both.如果只指定了一个名称空间,则它将同时用于这两个名称空间。
4.3. Exceptions例外情况¶
Exceptions are a means of breaking out of the normal flow of control of a code block in order to handle errors or other exceptional conditions. 异常是为了处理错误或其他异常情况而打破代码块正常控制流的一种手段。An exception is raised at the point where the error is detected; it may be handled by the surrounding code block or by any code block that directly or indirectly invoked the code block where the error occurred.在检测到错误的点引发异常;它可以由周围的代码块处理,也可以由直接或间接调用发生错误的代码块的任何代码块处理。
The Python interpreter raises an exception when it detects a run-time error (such as division by zero). Python解释器在检测到运行时错误(例如除以零)时引发异常。A Python program can also explicitly raise an exception with the Python程序还可以使用raise
statement. raise
语句显式引发异常。Exception handlers are specified with the 使用try
… except
statement. try
… except
语句指定异常处理程序。The 此类语句的finally
clause of such a statement can be used to specify cleanup code which does not handle the exception, but is executed whether an exception occurred or not in the preceding code.finally
子句可用于指定不处理异常的清理代码,但无论前面的代码中是否发生异常,都会执行该清理代码。
Python uses the “termination” model of error handling: an exception handler can find out what happened and continue execution at an outer level, but it cannot repair the cause of the error and retry the failing operation (except by re-entering the offending piece of code from the top).Python使用错误处理的“终止”模型:异常处理程序可以找出发生的情况并在外部级别继续执行,但它无法修复错误原因并重试失败的操作(除非从顶部重新输入有问题的代码)。
When an exception is not handled at all, the interpreter terminates execution of the program, or returns to its interactive main loop. 当一个异常根本没有被处理时,解释器终止程序的执行,或返回到其交互式主循环。In either case, it prints a stack traceback, except when the exception is 无论哪种情况,它都会打印堆栈回溯,除非异常为SystemExit
.SystemExit
。
Exceptions are identified by class instances. 异常由类实例标识。The 根据实例的类选择except
clause is selected depending on the class of the instance: it must reference the class of the instance or a non-virtual base class thereof. except
子句:它必须引用实例的类或其非虚拟基类。The instance can be received by the handler and can carry additional information about the exceptional condition.处理程序可以接收实例,并可以携带有关异常情况的附加信息。
Note
Exception messages are not part of the Python API. 异常消息不是Python API的一部分。Their contents may change from one version of Python to the next without warning and should not be relied on by code which will run under multiple versions of the interpreter.它们的内容可能会在没有警告的情况下从Python的一个版本更改到下一个版本,并且不应该被在多个版本的解释器下运行的代码所依赖。
See also the description of the 另请参见try
statement in section The try statement and raise
statement in section The raise statement.try
语句一节中try
语句的描述和raise
语句一节中的raise
语句。
Footnotes
- 1
This limitation occurs because the code that is executed by these operations is not available at the time the module is compiled.出现这种限制是因为在编译模块时,这些操作执行的代码不可用。