“Python/docs/3.9/reference/executionmodel”的版本间差异

来自菜鸟教程
Python/docs/3.9/reference/executionmodel
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:4. 执行模型 — Python 文档}}
 
<div id="execution-model" class="section">
 
<div id="execution-model" class="section">
  
 
<span id="execmodel"></span>
 
<span id="execmodel"></span>
= <span class="section-number">4. </span>Execution model =
+
= 4. 执行模型 =
  
 
<div id="structure-of-a-program" class="section">
 
<div id="structure-of-a-program" class="section">
  
 
<span id="prog-structure"></span><span id="index-0"></span>
 
<span id="prog-structure"></span><span id="index-0"></span>
== <span class="section-number">4.1. </span>Structure of a program ==
+
== 4.1. 程序的结构 ==
  
A Python program is constructed from code blocks.
+
Python 程序由代码块构成。 ''block'' 是作为一个单元执行的一段 Python 程序文本。 以下是块:模块、函数体和类定义。 以交互方式键入的每个命令都是一个块。 脚本文件(作为解释器的标准输入或指定为解释器的命令行参数的文件)是一个代码块。 脚本命令(在解释器命令行上使用 [[../../using/cmdline#cmdoption-c|-c]] 选项指定的命令)是一个代码块。 从命令行使用 [[../../using/cmdline#cmdoption-m|-m]] 参数作为顶级脚本(作为模块 <code>__main__</code>)运行的模块也是一个代码块。 传递给内置函数 [[../../library/functions#eval|eval()]] [[../../library/functions#exec|exec()]] 的字符串参数是一个代码块。
A ''block'' is a piece of Python program text that is executed as a unit.
 
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 [[../../using/cmdline#cmdoption-c|<code>-c</code>]] option) is a code block.
 
A module run as a top level script (as module <code>__main__</code>) from the command
 
line using a [[../../using/cmdline#cmdoption-m|<code>-m</code>]] argument is also a code block. The string
 
argument passed to the built-in functions [[../../library/functions#eval|<code>eval()</code>]] and [[../../library/functions#exec|<code>exec()</code>]] is a
 
code block.
 
  
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.
 
  
  
第30行: 第19行:
  
 
<span id="naming"></span>
 
<span id="naming"></span>
== <span class="section-number">4.2. </span>Naming and binding ==
+
== 4.2. 命名和绑定 ==
  
 
<div id="binding-of-names" class="section">
 
<div id="binding-of-names" class="section">
  
 
<span id="bind-names"></span><span id="index-3"></span>
 
<span id="bind-names"></span><span id="index-3"></span>
=== <span class="section-number">4.2.1. </span>Binding of names ===
+
=== 4.2.1. 名称绑定 ===
  
''Names'' refer to objects. Names are introduced by name binding operations.
+
''名称'' 指的是对象。 名称由名称绑定操作引入。
  
The following constructs bind names: formal parameters to functions,
+
以下构造绑定名称:函数的形式参数、[[../simple_stmts#import|import]] 语句、类和函数定义(这些绑定定义块中的类或函数名称)以及作为标识符的目标(如果出现在赋值中),[ X255X]for 循环头,或在 [[../compound_stmts#with|with]] 语句或 [[../compound_stmts#except|except]] 子句中的 <code>as</code> 之后。 形式为 <code>from ... import *</code> <code>import</code> 语句绑定了导入模块中定义的所有名称,但以下划线开头的名称除外。 此表单只能在模块级别使用。
[[../simple_stmts#import|<code>import</code>]] statements, class and function definitions (these bind the
 
class or function name in the defining block), and targets that are identifiers
 
if occurring in an assignment, [[../compound_stmts#for|<code>for</code>]] loop header, or after
 
<code>as</code> in a [[../compound_stmts#with|<code>with</code>]] statement or [[../compound_stmts#except|<code>except</code>]] clause.
 
The <code>import</code> statement
 
of the form <code>from ... import *</code> binds all names defined in the imported
 
module, except those beginning with an underscore. This form may only be used
 
at the module level.
 
  
A target occurring in a [[../simple_stmts#del|<code>del</code>]] statement is also considered bound for
+
出现在 [[../simple_stmts#del|del]] 语句中的目标也被认为是为此目的绑定的(尽管实际语义是解除名称的绑定)。
this purpose (though the actual semantics are to unbind the name).
 
  
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
+
如果名称绑定在块中,则它是该块的局部变量,除非声明为 [[../simple_stmts#nonlocal|nonlocal]] [[../simple_stmts#global|global]]。 如果名称绑定在模块级别,则它是一个全局变量。 (模块代码块的变量是局部的和全局的。)如果一个变量在代码块中使用但没有在那里定义,它是一个''自由变量''
declared as [[../simple_stmts#nonlocal|<code>nonlocal</code>]] or [[../simple_stmts#global|<code>global</code>]]. 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
+
程序文本中每次出现的名称都引用由以下名称解析规则建立的该名称的 ''binding''
that name established by the following name resolution rules.
 
  
  
第69行: 第43行:
  
 
<span id="resolve-names"></span>
 
<span id="resolve-names"></span>
=== <span class="section-number">4.2.2. </span>Resolution of names ===
+
=== 4.2.2. 名称解析 ===
  
A ''scope'' defines the visibility of a name within a block. If a local
+
''scope'' 定义块内名称的可见性。 如果在块中定义了局部变量,则其作用域包括该块。 如果定义出现在功能块中,则范围扩展到定义块中包含的任何块,除非包含的块为名称引入了不同的绑定。
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 [[../../library/exceptions#NameError|<code>NameError</code>]] exception is raised.
+
如果根本找不到名称,则会引发 [[../../library/exceptions#NameError|NameError]] 异常。 如果当前作用域是一个函数作用域,并且该名称引用了一个在使用该名称时尚未绑定到值的局部变量,则会引发 [[../../library/exceptions#UnboundLocalError|UnboundLocalError]] 异常。 [[../../library/exceptions#UnboundLocalError|UnboundLocalError]] [[../../library/exceptions#NameError|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 [[../../library/exceptions#UnboundLocalError|<code>UnboundLocalError</code>]] exception is raised.
 
[[../../library/exceptions#UnboundLocalError|<code>UnboundLocalError</code>]] is a subclass of [[../../library/exceptions#NameError|<code>NameError</code>]].
 
  
If a name binding operation occurs anywhere within a code block, all uses of the
+
如果名称绑定操作发生在代码块内的任何位置,则块内对该名称的所有使用都被视为对当前块的引用。 在绑定之前在块中使用名称时,这可能会导致错误。 这个规则很微妙。 Python 缺少声明并允许名称绑定操作发生在代码块中的任何位置。 代码块的局部变量可以通过扫描块的整个文本进行名称绑定操作来确定。
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. The local variables of a code block can be
 
determined by scanning the entire text of the block for name binding operations.
 
  
If the [[../simple_stmts#global|<code>global</code>]] statement occurs within a block, all uses of the name
+
如果 [[../simple_stmts#global|global]] 语句出现在一个块中,则该语句中指定的名称的所有使用都引用顶级命名空间中这些名称的绑定。 通过搜索全局命名空间,在顶级命名空间中解析名称,即 包含代码块的模块的命名空间,以及 builtins 命名空间,模块 [[../../library/builtins#module-builtins|builtins]] 的命名空间。 首先搜索全局命名空间。 如果在那里找不到名称,则搜索内置命名空间。 <code>global</code> 语句必须在所有列出名称的使用之前。
specified in the statement refer to the binding of that name in the top-level
 
namespace. 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 [[../../library/builtins#module-builtins|<code>builtins</code>]]. The
 
global namespace is searched first. If the name is not found there, the
 
builtins namespace is searched. The <code>global</code> statement must precede
 
all uses of the name.
 
  
The [[../simple_stmts#global|<code>global</code>]] statement has the same scope as a name binding operation
+
[[../simple_stmts#global|global]] 语句与同一块中的名称绑定操作具有相同的作用域。 如果自由变量最近的封闭作用域包含全局语句,则自由变量被视为全局变量。
in the same block. If the nearest enclosing scope for a free variable contains
 
a global statement, the free variable is treated as a global.
 
  
The [[../simple_stmts#nonlocal|<code>nonlocal</code>]] statement causes corresponding names to refer
+
[[../simple_stmts#nonlocal|nonlocal]] 语句使相应的名称引用最近的封闭函数作用域中先前绑定的变量。 [[../../library/exceptions#SyntaxError|SyntaxError]] 如果给定的名称不存在于任何封闭的函数范围内,则会在编译时引发。
to previously bound variables in the nearest enclosing function scope.
 
[[../../library/exceptions#SyntaxError|<code>SyntaxError</code>]] 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
+
模块的命名空间在第一次导入模块时自动创建。 脚本的主模块始终称为 [[../../library/__main__#module-__main__|__main__]]
imported. The main module for a script is always called [[../../library/__main__#module-__main__|<code>__main__</code>]].
 
  
Class definition blocks and arguments to [[../../library/functions#exec|<code>exec()</code>]] and [[../../library/functions#eval|<code>eval()</code>]] are
+
[[../../library/functions#exec|exec()]] [[../../library/functions#eval|eval()]] 的类定义块和参数在名称解析的上下文中是特殊的。 类定义是可以使用和定义名称的可执行语句。 这些引用遵循名称解析的正常规则,例外是在全局命名空间中查找未绑定的局部变量。 类定义的命名空间成为类的属性字典。 类块中定义的名称范围仅限于类块; 它没有扩展到方法的代码块——这包括推导式和生成器表达式,因为它们是使用函数作用域实现的。 这意味着以下操作将失败:
special in the context of name resolution.
 
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:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第130行: 第67行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class A:
+
<syntaxhighlight lang="python3">class A:
 
     a = 42
 
     a = 42
     b = list(a + i for i in range(10))</pre>
+
     b = list(a + i for i in range(10))</syntaxhighlight>
  
 
</div>
 
</div>
第142行: 第79行:
  
 
<span id="restrict-exec"></span>
 
<span id="restrict-exec"></span>
=== <span class="section-number">4.2.3. </span>Builtins and restricted execution ===
+
=== 4.2.3. 内置函数和受限执行 ===
  
<div id="index-11" class="impl-detail compound">
+
与代码块执行相关的内置命名空间实际上是通过在其全局命名空间中查找名称 <code>__builtins__</code> 来找到的; 这应该是字典或模块(在后一种情况下使用模块的字典)。 默认情况下,在[[../../library/__main__#module-__main__|__main__]]模块中时,<code>__builtins__</code>为内置模块[[../../library/builtins#module-builtins|builtins]]; 当在任何其他模块中时,<code>__builtins__</code> [[../../library/builtins#module-builtins|builtins]] 模块本身字典的别名。
 
 
'''CPython implementation detail:''' Users should not touch <code>__builtins__</code>; it is strictly an implementation
 
detail. Users wanting to override values in the builtins namespace should
 
[[../simple_stmts#import|<code>import</code>]] the [[../../library/builtins#module-builtins|<code>builtins</code>]] module and modify its
 
attributes appropriately.
 
 
 
 
 
</div>
 
The builtins namespace associated with the execution of a code block
 
is actually found by looking up the name <code>__builtins__</code> in its
 
global namespace; this should be a dictionary or a module (in the
 
latter case the module's dictionary is used). By default, when in the
 
[[../../library/__main__#module-__main__|<code>__main__</code>]] module, <code>__builtins__</code> is the built-in module
 
[[../../library/builtins#module-builtins|<code>builtins</code>]]; when in any other module, <code>__builtins__</code> is an
 
alias for the dictionary of the [[../../library/builtins#module-builtins|<code>builtins</code>]] module itself.
 
  
  
第166行: 第88行:
  
 
<span id="dynamic-features"></span>
 
<span id="dynamic-features"></span>
=== <span class="section-number">4.2.4. </span>Interaction with dynamic features ===
+
=== 4.2.4. 与动态特征的交互 ===
  
Name resolution of free variables occurs at runtime, not at compile time.
+
自由变量的名称解析发生在运行时,而不是编译时。 这意味着以下代码将打印 42:
This means that the following code will print 42:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第175行: 第96行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>i = 10
+
<syntaxhighlight lang="python3">i = 10
 
def f():
 
def f():
 
     print(i)
 
     print(i)
 
i = 42
 
i = 42
f()</pre>
+
f()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[../../library/functions#eval|<code>eval()</code>]] and [[../../library/functions#exec|<code>exec()</code>]] functions do not have access to the full
+
[[../../library/functions#eval|eval()]] [[../../library/functions#exec|exec()]] 函数无法访问用于解析名称的完整环境。 名称可以在调用者的本地和全局命名空间中解析。 自由变量不在最近的封闭命名空间中解析,而是在全局命名空间中解析。 [[#id3|1]] [[../../library/functions#exec|exec()]] [[../../library/functions#eval|eval()]] 函数有可选参数来覆盖全局和本地命名空间。 如果只指定了一个命名空间,则两者都使用它。
environment for resolving names. 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. [[#id3|1]] The [[../../library/functions#exec|<code>exec()</code>]] and
 
[[../../library/functions#eval|<code>eval()</code>]] functions have optional arguments to override the global and local
 
namespace. If only one namespace is specified, it is used for both.
 
  
  
第198行: 第114行:
  
 
<span id="id2"></span>
 
<span id="id2"></span>
== <span class="section-number">4.3. </span>Exceptions ==
+
== 4.3. 例外 ==
  
 
<span id="index-12" class="target"></span>
 
<span id="index-12" class="target"></span>
Exceptions are a means of breaking out of the normal flow of control of a code
+
异常是一种打破代码块正常控制流以处理错误或其他异常情况的手段。 一个例外是在检测到错误的点 ''raised''; 它可能由周围的代码块或任何直接或间接调用发生错误的代码块的代码块 ''处理''
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
+
Python 解释器在检测到运行时错误(例如被零除)时会引发异常。 Python 程序还可以使用 [[../simple_stmts#raise|raise]] 语句显式引发异常。 异常处理程序由 [[../compound_stmts#try|try]] ... [[../compound_stmts#except|except]] 语句指定。 此类语句的 [[../compound_stmts#finally|finally]] 子句可用于指定不处理异常的清理代码,但无论前面代码中是否发生异常,都会执行该代码。
(such as division by zero). A Python program can also explicitly raise an
 
exception with the [[../simple_stmts#raise|<code>raise</code>]] statement. Exception handlers are specified
 
with the [[../compound_stmts#try|<code>try</code>]] ... [[../compound_stmts#except|<code>except</code>]] statement. The [[../compound_stmts#finally|<code>finally</code>]]
 
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.
 
  
Python uses the &quot;termination&quot; model of error handling: an exception handler can
+
Python 使用错误处理的“终止”模型:异常处理程序可以找出发生了什么并在外层继续执行,但它不能修复错误的原因并重试失败的操作(除非重新进入有问题的部分)顶部的代码)。
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).
 
  
When an exception is not handled at all, the interpreter terminates execution of
+
当根本没有处理异常时,解释器终止程序的执行,或返回到它的交互式主循环。 在任何一种情况下,它都会打印堆栈回溯,除非异常是 [[../../library/exceptions#SystemExit|SystemExit]]
the program, or returns to its interactive main loop. In either case, it prints
 
a stack traceback, except when the exception is [[../../library/exceptions#SystemExit|<code>SystemExit</code>]].
 
  
Exceptions are identified by class instances. The [[../compound_stmts#except|<code>except</code>]] clause is
+
异常由类实例标识。 [[../compound_stmts#except|except]] 子句的选择取决于实例的类:它必须引用实例的类或其基类。 实例可以被处理程序接收,并且可以携带有关异常情况的附加信息。
selected depending on the class of the instance: it must reference the class of
 
the instance or a base class thereof. The instance can be received by the
 
handler and can carry additional information about the exceptional condition.
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
Exception messages are not part of the Python API. Their contents may change
+
异常消息不是 Python API 的一部分。 它们的内容可能会在没有警告的情况下从 Python 的一个版本更改为下一个版本,并且不应依赖将在多个版本的解释器下运行的代码。
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.
 
  
  
 
</div>
 
</div>
See also the description of the [[../compound_stmts#try|<code>try</code>]] statement in section [[../compound_stmts#try|<span class="std std-ref">The try statement</span>]]
+
另请参阅 [[../compound_stmts#try|节中的]] [[../compound_stmts#try|try]] 语句的描述[[../simple_stmts#raise|raise 语句]] 节中的 try 语句 和 [[../simple_stmts#raise|raise]] 语句。
and [[../simple_stmts#raise|<code>raise</code>]] statement in section [[../simple_stmts#raise|<span class="std std-ref">The raise statement</span>]].
 
  
Footnotes
+
脚注
  
 
; <span class="brackets">[[#id1|1]]</span>
 
; <span class="brackets">[[#id1|1]]</span>
: This limitation occurs because the code that is executed by these operations is not available at the time the module is compiled.
+
: 出现此限制是因为这些操作执行的代码在编译模块时不可用。
 +
 
  
 +
</div>
  
 
</div>
 
</div>
 +
<div class="clearer">
 +
 +
  
 
</div>
 
</div>
  
[[Category:Python 3.9 中文文档]]
+
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:54的最新版本

4. 执行模型

4.1. 程序的结构

Python 程序由代码块构成。 block 是作为一个单元执行的一段 Python 程序文本。 以下是块:模块、函数体和类定义。 以交互方式键入的每个命令都是一个块。 脚本文件(作为解释器的标准输入或指定为解释器的命令行参数的文件)是一个代码块。 脚本命令(在解释器命令行上使用 -c 选项指定的命令)是一个代码块。 从命令行使用 -m 参数作为顶级脚本(作为模块 __main__)运行的模块也是一个代码块。 传递给内置函数 eval()exec() 的字符串参数是一个代码块。

代码块在 执行帧 中执行。 帧包含一些管理信息(用于调试)并确定代码块执行完成后继续执行的位置和方式。


4.2. 命名和绑定

4.2.1. 名称绑定

名称 指的是对象。 名称由名称绑定操作引入。

以下构造绑定名称:函数的形式参数、import 语句、类和函数定义(这些绑定定义块中的类或函数名称)以及作为标识符的目标(如果出现在赋值中),[ X255X]for 循环头,或在 with 语句或 except 子句中的 as 之后。 形式为 from ... import *import 语句绑定了导入模块中定义的所有名称,但以下划线开头的名称除外。 此表单只能在模块级别使用。

出现在 del 语句中的目标也被认为是为此目的绑定的(尽管实际语义是解除名称的绑定)。

每个赋值或导入语句都出现在由类或函数定义或模块级别(顶级代码块)定义的块中。

如果名称绑定在块中,则它是该块的局部变量,除非声明为 nonlocalglobal。 如果名称绑定在模块级别,则它是一个全局变量。 (模块代码块的变量是局部的和全局的。)如果一个变量在代码块中使用但没有在那里定义,它是一个自由变量

程序文本中每次出现的名称都引用由以下名称解析规则建立的该名称的 binding


4.2.2. 名称解析

scope 定义块内名称的可见性。 如果在块中定义了局部变量,则其作用域包括该块。 如果定义出现在功能块中,则范围扩展到定义块中包含的任何块,除非包含的块为名称引入了不同的绑定。

在代码块中使用名称时,将使用最近的封闭范围对其进行解析。 代码块可见的所有此类范围的集合称为块的 环境

如果根本找不到名称,则会引发 NameError 异常。 如果当前作用域是一个函数作用域,并且该名称引用了一个在使用该名称时尚未绑定到值的局部变量,则会引发 UnboundLocalError 异常。 UnboundLocalErrorNameError 的子类。

如果名称绑定操作发生在代码块内的任何位置,则块内对该名称的所有使用都被视为对当前块的引用。 在绑定之前在块中使用名称时,这可能会导致错误。 这个规则很微妙。 Python 缺少声明并允许名称绑定操作发生在代码块中的任何位置。 代码块的局部变量可以通过扫描块的整个文本进行名称绑定操作来确定。

如果 global 语句出现在一个块中,则该语句中指定的名称的所有使用都引用顶级命名空间中这些名称的绑定。 通过搜索全局命名空间,在顶级命名空间中解析名称,即 包含代码块的模块的命名空间,以及 builtins 命名空间,模块 builtins 的命名空间。 首先搜索全局命名空间。 如果在那里找不到名称,则搜索内置命名空间。 global 语句必须在所有列出名称的使用之前。

global 语句与同一块中的名称绑定操作具有相同的作用域。 如果自由变量最近的封闭作用域包含全局语句,则自由变量被视为全局变量。

nonlocal 语句使相应的名称引用最近的封闭函数作用域中先前绑定的变量。 SyntaxError 如果给定的名称不存在于任何封闭的函数范围内,则会在编译时引发。

模块的命名空间在第一次导入模块时自动创建。 脚本的主模块始终称为 __main__

exec()eval() 的类定义块和参数在名称解析的上下文中是特殊的。 类定义是可以使用和定义名称的可执行语句。 这些引用遵循名称解析的正常规则,例外是在全局命名空间中查找未绑定的局部变量。 类定义的命名空间成为类的属性字典。 类块中定义的名称范围仅限于类块; 它没有扩展到方法的代码块——这包括推导式和生成器表达式,因为它们是使用函数作用域实现的。 这意味着以下操作将失败:

class A:
    a = 42
    b = list(a + i for i in range(10))

4.2.3. 内置函数和受限执行

与代码块执行相关的内置命名空间实际上是通过在其全局命名空间中查找名称 __builtins__ 来找到的; 这应该是字典或模块(在后一种情况下使用模块的字典)。 默认情况下,在__main__模块中时,__builtins__为内置模块builtins; 当在任何其他模块中时,__builtins__builtins 模块本身字典的别名。


4.2.4. 与动态特征的交互

自由变量的名称解析发生在运行时,而不是编译时。 这意味着以下代码将打印 42:

i = 10
def f():
    print(i)
i = 42
f()

eval()exec() 函数无法访问用于解析名称的完整环境。 名称可以在调用者的本地和全局命名空间中解析。 自由变量不在最近的封闭命名空间中解析,而是在全局命名空间中解析。 1 exec()eval() 函数有可选参数来覆盖全局和本地命名空间。 如果只指定了一个命名空间,则两者都使用它。


4.3. 例外

异常是一种打破代码块正常控制流以处理错误或其他异常情况的手段。 一个例外是在检测到错误的点 raised; 它可能由周围的代码块或任何直接或间接调用发生错误的代码块的代码块 处理

Python 解释器在检测到运行时错误(例如被零除)时会引发异常。 Python 程序还可以使用 raise 语句显式引发异常。 异常处理程序由 try ... except 语句指定。 此类语句的 finally 子句可用于指定不处理异常的清理代码,但无论前面代码中是否发生异常,都会执行该代码。

Python 使用错误处理的“终止”模型:异常处理程序可以找出发生了什么并在外层继续执行,但它不能修复错误的原因并重试失败的操作(除非重新进入有问题的部分)顶部的代码)。

当根本没有处理异常时,解释器终止程序的执行,或返回到它的交互式主循环。 在任何一种情况下,它都会打印堆栈回溯,除非异常是 SystemExit

异常由类实例标识。 except 子句的选择取决于实例的类:它必须引用实例的类或其基类。 实例可以被处理程序接收,并且可以携带有关异常情况的附加信息。

笔记

异常消息不是 Python API 的一部分。 它们的内容可能会在没有警告的情况下从 Python 的一个版本更改为下一个版本,并且不应依赖将在多个版本的解释器下运行的代码。


另请参阅 节中的 try 语句的描述raise 语句 节中的 try 语句 和 raise 语句。

脚注

1
出现此限制是因为这些操作执行的代码在编译模块时不可用。