7. Simple statements简单语句

A simple statement is comprised within a single logical line. 简单语句包含在单个逻辑行中。Several simple statements may occur on a single line separated by semicolons. 几条简单语句可能出现在用分号分隔的单行上。The syntax for simple statements is:简单语句的语法为:


simple_stmt ::= expression_stmt
| assert_stmt
| assignment_stmt
| augmented_assignment_stmt
| annotated_assignment_stmt
| pass_stmt
| del_stmt
| return_stmt
| yield_stmt
| raise_stmt
| break_stmt
| continue_stmt
| import_stmt
| future_stmt
| global_stmt
| nonlocal_stmt

7.1. Expression statements表达式语句

Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful result; in Python, procedures return the value None). 表达式语句(主要以交互方式)用于计算和写入值,或(通常)调用过程(一个不返回有意义结果的函数;在Python中,过程返回值None)。Other uses of expression statements are allowed and occasionally useful. 允许使用表达式语句的其他用途,有时也很有用。The syntax for an expression statement is:表达式语句的语法为:


expression_stmt ::= starred_expression

An expression statement evaluates the expression list (which may be a single expression).表达式语句计算表达式列表(可能是单个表达式)。

In interactive mode, if the value is not None, it is converted to a string using the built-in repr() function and the resulting string is written to standard output on a line by itself (except if the result is None, so that procedure calls do not cause any output.)在交互模式下,如果值不是None,则使用内置的repr()函数将其转换为字符串,并将生成的字符串自身写入一行上的标准输出(除非结果为None,以便过程调用不会导致任何输出)

7.2. Assignment statements赋值语句

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:赋值语句用于(重新)将名称绑定到值,并修改可变对象的属性或项:


assignment_stmt ::= (target_list "=")+ (starred_expression | yield_expression)
target_list ::= target ("," target)* [","]
target ::= identifier
| "(" [target_list] ")"
| "[" [target_list] "]"
| attributeref
| subscription
| slicing
| "*" target

(See section Primaries for the syntax definitions for attributeref, subscription, and slicing.)(有关attributerefsubscriptionslicing的语法定义,请参阅初选一节。)

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.赋值语句计算表达式列表(请记住,这可以是单个表达式或逗号分隔列表,后者生成元组),并从左到右将单个结果对象分配给每个目标列表。

Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. 根据目标(列表)的形式递归定义赋值。当目标是可变对象(属性引用、订阅或切片)的一部分时,可变对象必须最终执行分配并决定其有效性,如果分配不可接受,则可能引发异常。The rules observed by various types and the exceptions raised are given with the definition of the object types (see section The standard type hierarchy).各种类型遵守的规则和引发的异常都是通过对象类型的定义给出的(请参见标准类型层次结构一节)。

Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.将对象分配到目标列表(可选地括在括号或方括号中)的递归定义如下。

  • If the target list is a single target with no trailing comma, optionally in parentheses, the object is assigned to that target.如果目标列表是一个没有尾随逗号的单一目标(可选地在括号中),则对象将被指定给该目标。

  • Else:其他:

    • If the target list contains one target prefixed with an asterisk, called a “starred” target: The object must be an iterable with at least as many items as there are targets in the target list, minus one. 如果目标列表包含一个以星号为前缀的目标,称为“星号”目标:该对象必须是一个iterable,其项目数至少与目标列表中的目标数相等,减去一。The first items of the iterable are assigned, from left to right, to the targets before the starred target. iterable的第一个项目从左到右分配给带星号目标之前的目标。The final items of the iterable are assigned to the targets after the starred target. iterable的最后一项分配给星号目标之后的目标。A list of the remaining items in the iterable is then assigned to the starred target (the list can be empty).然后将iterable中剩余项的列表分配给带星号的目标(列表可以为空)。

    • Else: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.否则:对象必须是一个iterable,其项数必须与目标列表中的目标数相同,并且这些项从左到右分配给相应的目标。

Assignment of an object to a single target is recursively defined as follows.将对象分配给单个目标的递归定义如下。

  • If the target is an identifier (name):如果目标是标识符(名称):

    • If the name does not occur in a global or nonlocal statement in the current code block: the name is bound to the object in the current local namespace.如果名称未出现在当前代码块的globalnonlocal语句中:则名称将绑定到当前本地命名空间中的对象。

    • Otherwise: the name is bound to the object in the global namespace or the outer namespace determined by nonlocal, respectively.否则:名称将分别绑定到全局名称空间或nonlocal确定的外部名称空间中的对象。

    The name is rebound if it was already bound. 如果名称已绑定,则名称为回弹。This may cause the reference count for the object previously bound to the name to reach zero, causing the object to be deallocated and its destructor (if it has one) to be called.这可能会导致之前绑定到名称的对象的引用计数达到零,从而导致对象被释放并调用其析构函数(如果有)。

  • If the target is an attribute reference: The primary expression in the reference is evaluated. 如果目标是属性引用:将计算引用中的主表达式。It should yield an object with assignable attributes; if this is not the case, TypeError is raised. 它应该产生一个具有可分配属性的对象;如果不是这样,则会引发TypeErrorThat object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily AttributeError).然后要求该对象将指定的对象指定给给定的属性;如果无法执行赋值,则会引发异常(通常但不一定是AttributeError)。

    Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the right-hand side expression, a.x can access either an instance attribute or (if no instance attribute exists) a class attribute. 注意:如果对象是类实例,并且属性引用发生在赋值运算符(右侧表达式)的两侧,a.x可以访问实例属性或(如果不存在实例属性)类属性。The left-hand side target a.x is always set as an instance attribute, creating it if necessary. 左侧目标a.x始终设置为实例属性,并在必要时创建它。Thus, the two occurrences of a.x do not necessarily refer to the same attribute: if the right-hand side expression refers to a class attribute, the left-hand side creates a new instance attribute as the target of the assignment:因此,a.x的两个引用不一定引用同一个属性:如果右侧表达式引用类属性,则左侧将创建一个新实例属性作为赋值的目标:

    class Cls:
    x = 3 # class variable
    inst = Cls()
    inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3

    This description does not necessarily apply to descriptor attributes, such as properties created with property().此描述不一定适用于描述符属性,例如使用property()创建的属性。

  • If the target is a subscription: The primary expression in the reference is evaluated. 如果目标是订阅:将计算引用中的主表达式。It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). 它应该生成可变序列对象(如列表)或映射对象(如字典)。Next, the subscript expression is evaluated.接下来,计算下标表达式。

    If the primary is a mutable sequence object (such as a list), the subscript must yield an integer. 如果主对象是可变序列对象(如列表),则下标必须生成一个整数。If it is negative, the sequence’s length is added to it. 如果为负,则将序列的长度添加到其中。The resulting value must be a nonnegative integer less than the sequence’s length, and the sequence is asked to assign the assigned object to its item with that index. 结果值必须是小于序列长度的非负整数,并要求序列将指定的对象分配给具有该索引的项。If the index is out of range, IndexError is raised (assignment to a subscripted sequence cannot add new items to a list).如果索引超出范围,则引发IndexError(对已订阅序列的赋值不能向列表中添加新项)。

    If the primary is a mapping object (such as a dictionary), the subscript must have a type compatible with the mapping’s key type, and the mapping is then asked to create a key/datum pair which maps the subscript to the assigned object. 如果主对象是映射对象(如字典),则下标的类型必须与映射的键类型兼容,然后要求映射创建键/基准对,将下标映射到指定的对象。This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed).这可以用相同的键值替换现有的键/值对,或者插入新的键/值对(如果不存在具有相同值的键)。

    For user-defined objects, the __setitem__() method is called with appropriate arguments.对于用户定义的对象,将使用适当的参数调用__setitem__()方法。

  • If the target is a slicing: The primary expression in the reference is evaluated. 如果目标是切片:将计算引用中的主表达式。It should yield a mutable sequence object (such as a list). 它应该生成一个可变序列对象(如列表)。The assigned object should be a sequence object of the same type. 指定的对象应为相同类型的序列对象。Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. 接下来,计算下限和上限表达式,只要它们存在;默认值为零和序列的长度。The bounds should evaluate to integers. 边界应计算为整数。If either bound is negative, the sequence’s length is added to it. 如果任何一个界限为负,则将序列的长度添加到该界限中。The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. 结果边界被剪裁为介于零和序列长度之间(包括零和序列长度)。Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. 最后,要求序列对象用指定序列的项目替换切片。The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the target sequence allows it.如果目标序列允许,切片的长度可能不同于分配序列的长度,从而改变目标序列的长度。

CPython implementation detail:CPython实施详情: In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages.在当前的实现中,目标的语法与表达式的语法相同,并且在代码生成阶段拒绝无效语法,从而导致错误消息不太详细。

Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. 虽然赋值的定义意味着左侧和右侧之间的重叠是“同时的”(例如a, b = b, a交换两个变量),但赋值给变量的集合中的重叠是从左到右发生的,有时会导致混淆。For instance, the following program prints [0, 2]:例如,以下程序打印[0, 2]

x = [0, 1]
i = 0
i, x[i] = 1, 2 # i is updated, then x[i] is updated
print(x)

See also

PEP 3132 - Extended Iterable Unpacking扩展Iterable拆箱

The specification for the *target feature.*target功能的规范。

7.2.1. Augmented assignment statements扩充赋值语句

Augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement:增广赋值是在一条语句中,二进制运算和赋值语句的组合:


augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)
augtarget ::= identifier | attributeref | subscription | slicing
augop ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
| ">>=" | "<<=" | "&=" | "^=" | "|="

(See section Primaries for the syntax definitions of the last three symbols.)(最后三个符号的语法定义见Primaries一节。)

An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. 增广赋值计算目标(与普通赋值语句不同,目标不能是解包)和表达式列表,对两个操作数执行特定于赋值类型的二进制运算,并将结果赋给原始目标。The target is only evaluated once.目标仅评估一次。

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. x+=1这样的增广赋值表达式可以重写为x=x+1,以获得类似但不完全相等的效果。In the augmented version, x is only evaluated once. 在增强版本中,x只计算一次。Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.此外,如果可能,实际操作将在原地执行,这意味着不创建新对象并将其分配给目标,而是修改旧对象。

Unlike normal assignments, augmented assignments evaluate the left-hand side before evaluating the right-hand side. 与普通赋值不同,增广赋值在求值右侧之前先求值左侧。For example, a[i] += f(x) first looks-up a[i], then it evaluates f(x) and performs the addition, and lastly, it writes the result back to a[i].例如,a[i] += f(x)首先查找a[i],然后计算f(x)并执行加法,最后将结果写回a[i]

With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. 除了在一条语句中分配给元组和多个目标之外,增广赋值语句所做的赋值与普通赋值的处理方式相同。Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations.类似地,除了可能的原地行为外,通过增广赋值执行的二进制操作与正常的二进制操作相同。

For targets which are attribute references, the same caveat about class and instance attributes applies as for regular assignments.对于作为属性引用的目标,关于类和实例属性的告诫与常规赋值的告诫相同。

7.2.2. Annotated assignment statements带注释的赋值语句

Annotation assignment is the combination, in a single statement, of a variable or attribute annotation and an optional assignment statement:注释赋值是在单个语句中,变量或属性注释与可选赋值语句的组合:


annotated_assignment_stmt ::= augtarget ":" expression
["=" (starred_expression | yield_expression)]

The difference from normal Assignment statements is that only single target is allowed.与常规赋值语句的区别在于,只允许使用单个目标。

For simple names as assignment targets, if in class or module scope, the annotations are evaluated and stored in a special class or module attribute __annotations__ that is a dictionary mapping from variable names (mangled if private) to evaluated annotations. 对于作为赋值目标的简单名称,如果在类或模块范围内,则注释将被计算并存储在特殊的类或模块属性__annotations__中,该属性是从变量名称(私有时损坏)到计算注释的字典映射。This attribute is writable and is automatically created at the start of class or module body execution, if annotations are found statically.此属性是可写的,如果静态找到注释,则会在类或模块体执行开始时自动创建该属性。

For expressions as assignment targets, the annotations are evaluated if in class or module scope, but not stored.对于作为赋值目标的表达式,注释在类或模块范围内进行计算,但不存储。

If a name is annotated in a function scope, then this name is local for that scope. 如果在函数作用域中注释了名称,则该名称是该作用域的本地名称。Annotations are never evaluated and stored in function scopes.注释从不计算并存储在函数作用域中。

If the right hand side is present, an annotated assignment performs the actual assignment before evaluating annotations (where applicable). 如果存在右侧,带注释的赋值将在评估批注之前执行实际赋值(如果适用)。If the right hand side is not present for an expression target, then the interpreter evaluates the target except for the last __setitem__() or __setattr__() call.如果表达式目标的右侧不存在,则解释器会计算该目标,但最后的__setitem__()__setattr__()调用除外。

See also

PEP 526 - Syntax for Variable Annotations变量注释的语法

The proposal that added syntax for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments.该提案增加了注释变量类型(包括类变量和实例变量)的语法,而不是通过注释来表达它们。

PEP 484 - Type hints

The proposal that added the typing module to provide a standard syntax for type annotations that can be used in static analysis tools and IDEs.该提案添加了typing模块,以提供可在静态分析工具和IDE中使用的类型注释的标准语法。

Changed in version 3.8:版本3.8中更改: Now annotated assignments allow same expressions in the right hand side as the regular assignments. 现在,带注释的赋值允许在右侧使用与常规赋值相同的表达式。Previously, some expressions (like un-parenthesized tuple expressions) caused a syntax error.以前,某些表达式(如未加括号的元组表达式)导致语法错误。

7.3. The assert statementassert语句

Assert statements are a convenient way to insert debugging assertions into a program:assert语句是将调试断言插入程序的一种方便方法:


assert_stmt ::= "assert" expression ["," expression]

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 expression1, expression2等效于

if __debug__:
if not expression1: raise AssertionError(expression2)

These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. 这些等价性假设__debug__AssertionError引用具有这些名称的内置变量。In the current implementation, the built-in variable __debug__ is True under normal circumstances, False when optimization is requested (command line option -O). 在当前实现中,内置变量__debug__在正常情况下为True,在请求优化时为False(命令行选项-O)。The current code generator emits no code for an assert statement when optimization is requested at compile time. 当在编译时请求优化时,当前代码生成器不会为assert语句发出任何代码。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.请注意,没有必要在错误消息中包含失败表达式的源代码;它将显示为堆栈跟踪的一部分。

Assignments to __debug__ are illegal. __debug__的分配是非法的。The value for the built-in variable is determined when the interpreter starts.内置变量的值在解释器启动时确定。

7.4. The pass statementpass语句


pass_stmt ::= "pass"

pass is a null operation — when it is executed, nothing happens. 是一个空操作——当它被执行时,不会发生任何事情。It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:当语法上需要语句,但不需要执行代码时,它可用作占位符,例如:

def f(arg): pass    # a function that does nothing (yet)
class C: pass # a class with no methods (yet)

7.5. The del statementdel语句


del_stmt ::= "del" target_list

Deletion is recursively defined very similar to the way assignment is defined. 删除是递归定义的,非常类似于分配的定义方式。Rather than spelling it out in full details, here are some hints.这里有一些提示,而不是详细地解释它。

Deletion of a target list recursively deletes each target, from left to right.删除目标列表会从左到右递归删除每个目标。

Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. 删除名称会从本地或全局命名空间中删除该名称的绑定,具体取决于该名称是否出现在同一代码块的global语句中。If the name is unbound, a NameError exception will be raised.如果名称未绑定,将引发NameError异常。

Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).属性引用、订阅和slicing的删除传递给所涉及的主要对象;删除切片通常相当于分配正确类型的空切片(但即使是这也是由切片对象决定的)。

Changed in version 3.2:版本3.2中更改: Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block.以前,如果名称作为嵌套块中的自由变量出现,则从本地命名空间中删除名称是非法的。

7.6. The return statementreturn语句


return_stmt ::= "return" [expression_list]

return may only occur syntactically nested in a function definition, not within a nested class definition.只能在语法上嵌套在函数定义中,而不是嵌套在类定义中。

If an expression list is present, it is evaluated, else None is substituted.如果存在表达式列表,则对其求值,否则None是替换。

return leaves the current function call with the expression list (or None) as return value.return以表达式列表(或None)作为返回值保留当前函数调用。

When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.return通过finally子句将控制权传递给try语句时,该finally子句将在真正离开函数之前执行。

In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. 在生成器函数中,return语句指示生成器已完成,并将引发StopIterationThe returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.返回的值(如果有)用作构造StopIteration的参数,并成为StopIteration.value属性。

In an asynchronous generator function, an empty return statement indicates that the asynchronous generator is done and will cause StopAsyncIteration to be raised. 在异步生成器函数中,空return语句表示异步生成器已完成,并将引发StopAsyncIterationA non-empty return statement is a syntax error in an asynchronous generator function.非空return语句是异步生成器函数中的语法错误。

7.7. The yield statementyield语句


yield_stmt ::= yield_expression

A yield statement is semantically equivalent to a yield expression. yield语句在语义上等价于yield表达式The yield statement can be used to omit the parentheses that would otherwise be required in the equivalent yield expression statement. yield语句可用于省略等效yield表达式语句中需要的括号。For example, the yield statements例如,yield语句

yield <expr>
yield from <expr>

are equivalent to the yield expression statements等价于yield表达式语句

(yield <expr>)
(yield from <expr>)

Yield expressions and statements are only used when defining a generator function, and are only used in the body of the generator function. 屈服表达式和语句仅在定义生成器函数时使用,并且仅在生成器函数的主体中使用。Using yield in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.在函数定义中使用yield足以使该定义创建一个生成器函数而不是普通函数。

For full details of yield semantics, refer to the Yield expressions section.有关yield语义的详细信息,请参阅yield表达式部分。

7.8. The raise statementraise语句


raise_stmt ::= "raise" [expression ["from" expression]]

If no expressions are present, raise re-raises the exception that is currently being handled, which is also known as the active exception. 如果不存在表达式,raise将重新引发当前正在处理的异常,该异常也称为活动异常。If there isn’t currently an active exception, a RuntimeError exception is raised indicating that this is an error.如果当前没有活动异常,将引发RuntimeError异常,指示这是一个错误。

Otherwise, raise evaluates the first expression as the exception object. 否则,raise将第一个表达式作为异常对象求值。It must be either a subclass or an instance of BaseException. 它必须是BaseException的子类或实例。If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.如果它是一个类,那么将在需要时通过实例化不带参数的类来获取异常实例。

The type of the exception is the exception instance’s class, the value is the instance itself.异常的类型是异常实例的类,是实例本身。

A traceback object is normally created automatically when an exception is raised and attached to it as the __traceback__ attribute, which is writable. 通常,当引发异常并将其作为__traceback__属性附加时,会自动创建回溯对象,该属性是可写的。You can create an exception and set your own traceback in one step using the with_traceback() exception method (which returns the same exception instance, with its traceback set to its argument), like so:可以使用with_traceback()异常方法(返回相同的异常实例,并将其回溯设置为其参数)创建一个异常并在一个步骤中设置自己的回溯,如下所示:

raise Exception("foo occurred").with_traceback(tracebackobj)

The from clause is used for exception chaining: if given, the second expression must be another exception class or instance. from子句用于异常链接:如果给定,第二个表达式必须是另一个异常类或实例。If the second expression is an exception instance, it will be attached to the raised exception as the __cause__ attribute (which is writable). 如果第二个表达式是异常实例,它将作为__cause__属性(可写)附加到引发的异常。If the expression is an exception class, the class will be instantiated and the resulting exception instance will be attached to the raised exception as the __cause__ attribute. 如果表达式是一个异常类,则该类将被实例化,生成的异常实例将作为__cause__属性附加到引发的异常。If the raised exception is not handled, both exceptions will be printed:如果未处理引发的异常,将打印两个异常:

>>> try:
... print(1 / 0)
... except Exception as exc:
... raise RuntimeError("Something bad happened") from exc
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened

A similar mechanism works implicitly if a new exception is raised when an exception is already being handled. 如果在已处理异常的情况下引发新异常,则类似的机制会隐式工作。An exception may be handled when an except or finally clause, or a with statement, is used. 当使用exceptfinally子句或with语句时,可以处理异常。The previous exception is then attached as the new exception’s __context__ attribute:然后,将以前的异常附加为新异常的__context__属性:

>>> try:
... print(1 / 0)
... except:
... raise RuntimeError("Something bad happened")
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened

Exception chaining can be explicitly suppressed by specifying None in the from clause:通过在from子句中指定None,可以显式抑制异常链接:

>>> try:
... print(1 / 0)
... except:
... raise RuntimeError("Something bad happened") from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened

Additional information on exceptions can be found in section Exceptions, and information about handling exceptions is in section The try statement.关于异常的其他信息可以在Exceptions部分中找到,关于处理异常的信息可以在try语句部分中找到。

Changed in version 3.3:版本3.3中更改: None is now permitted as Y in raise X from Y.raise X from Y中,现在允许YNone了。

New in version 3.3.版本3.3中新增。The __suppress_context__ attribute to suppress automatic display of the exception context.__suppress_context__属性用于抑制自动显示异常上下文。

7.9. The break statementbreak语句


break_stmt ::= "break"

break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.break只能以语法嵌套在forwhile循环中,而不能嵌套在该循环中的函数或类定义中。

It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.它终止最近的封闭循环,如果循环有一个,则跳过可选的else子句。

If a for loop is terminated by break, the loop control target keeps its current value.如果for循环因break而终止,则循环控制目标将保持其当前值。

When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.break使用finally子句将控制权从try语句中传递出去时,该finally子句将在真正离开循环之前执行。

7.10. The continue statementcontinue语句


continue_stmt ::= "continue"

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop. continue只能以语法嵌套在forwhile循环中,而不能嵌套在该循环中的函数或类定义中。It continues with the next cycle of the nearest enclosing loop.它将继续最近的封闭循环的下一个循环。

When continue passes control out of a try statement with a finally clause, that finally clause is executed before really starting the next loop cycle.continuefinally子句将控制权传递给try语句时,该finally子句将在真正开始下一个循环周期之前执行。

7.11. The import statementimport语句


import_stmt ::= "import" module ["as" identifier] ("," module ["as" identifier])*
| "from" relative_module "import" identifier ["as" identifier]
("," identifier ["as" identifier])*
| "from" relative_module "import" "(" identifier ["as" identifier]
("," identifier ["as" identifier])* [","] ")"
| "from" relative_module "import" "*"
module ::= (identifier ".")* identifier
relative_module ::= "."* module | "."+

The basic import statement (no from clause) is executed in two steps:基本导入语句(no from子句)分两步执行:

  1. find a module, loading and initializing it if necessary查找模块,必要时加载并初始化它

  2. define a name or names in the local namespace for the scope where the import statement occurs.在本地命名空间中为发生import语句的作用域定义一个或多个名称。

When the statement contains multiple clauses (separated by commas) the two steps are carried out separately for each clause, just as though the clauses had been separated out into individual import statements.当语句包含多个子句(用逗号分隔)时,将为每个子句分别执行这两个步骤,就像这些子句已被分隔为单独的导入语句一样。

The details of the first step, finding and loading modules are described in greater detail in the section on the import system, which also describes the various types of packages and modules that can be imported, as well as all the hooks that can be used to customize the import system. 关于导入系统的部分更详细地描述了第一步查找和加载模块的细节,该部分还描述了可导入的各种类型的包和模块,以及可用于自定义导入系统的所有挂钩。Note that failures in this step may indicate either that the module could not be located, or that an error occurred while initializing the module, which includes execution of the module’s code.请注意,此步骤中的故障可能表示无法定位模块,或者在初始化模块时发生错误,其中包括执行模块代码。

If the requested module is retrieved successfully, it will be made available in the local namespace in one of three ways:如果成功检索到请求的模块,将通过以下三种方式之一在本地命名空间中提供该模块:

  • If the module name is followed by as, then the name following as is bound directly to the imported module.如果模块名称后跟as,则as后面的名称将直接绑定到导入的模块。

  • If no other name is specified, and the module being imported is a top level module, the module’s name is bound in the local namespace as a reference to the imported module如果未指定其他名称,并且要导入的模块是顶级模块,则该模块的名称将绑定在本地命名空间中,作为对导入模块的引用

  • If the module being imported is not a top level module, then the name of the top level package that contains the module is bound in the local namespace as a reference to the top level package. 如果要导入的模块不是顶级模块,则包含该模块的顶级包的名称将绑定在本地命名空间中,作为对顶级包的引用。The imported module must be accessed using its full qualified name rather than directly必须使用导入的模块的完整限定名而不是直接访问该模块

The from form uses a slightly more complex process:from表单使用稍微复杂一些的过程:

  1. find the module specified in the from clause, loading and initializing it if necessary;查找from子句中指定的模块,必要时加载并初始化它;

  2. for each of the identifiers specified in the import clauses:对于import子句中指定的每个标识符:

    1. check if the imported module has an attribute by that name检查导入的模块是否具有该名称的属性

    2. if not, attempt to import a submodule with that name and then check the imported module again for that attribute如果没有,请尝试导入具有该名称的子模块,然后再次检查导入模块中的该属性

    3. if the attribute is not found, ImportError is raised.如果未找到该属性,则引发ImportError

    4. otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name否则,对该值的引用将存储在本地命名空间中,如果存在,则使用as子句中的名称,否则使用属性名称

Examples:示例:

import foo                 # foo imported and bound locally
import foo.bar.baz # foo.bar.baz imported, foo bound locally
import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb
from foo.bar import baz # foo.bar.baz imported and bound as baz
from foo import attr # foo imported and foo.attr bound as attr

If the list of identifiers is replaced by a star ('*'), all public names defined in the module are bound in the local namespace for the scope where the import statement occurs.如果标识符列表被星号('*')替换,则模块中定义的所有公共名称都将绑定到import语句所在范围的本地命名空间中。

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. 模块定义的公共名称是通过检查模块的命名空间中是否有一个名为__all__的变量来确定的;如果定义了,它必须是一个字符串序列,该字符串序列是由该模块定义或导入的名称。The names given in __all__ are all considered public and are required to exist. __all__中给出的名称都被视为公共名称,并且必须存在。If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_'). 如果未定义__all__,则公用名称集包括模块命名空间中找到的所有名称,这些名称不以下划线('_')开头。__all__ should contain the entire public API. __all__应包含整个公共API。It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).它旨在避免意外导出不属于API的项目(例如导入并在模块中使用的库模块)。

The wild card form of import — from module import * — is only allowed at the module level. 仅允许在模块级别使用通配符形式的导入:from module import *Attempting to use it in class or function definitions will raise a SyntaxError.试图在类或函数定义中使用它将引发SyntaxError

When specifying what module to import you do not have to specify the absolute name of the module. 指定要导入的模块时,不必指定模块的绝对名称。When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. 当一个模块或包包含在另一个包中时,可以在同一个顶层包中进行相对导入,而无需提及包名称。By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. 通过在from之后的指定模块或包中使用前导点,可以指定向上遍历当前包层次结构的高度,而无需指定确切的名称。One leading dot means the current package where the module making the import exists. 一个前导点表示进行导入的模块所在的当前包。Two dots means up one package level. 两个点表示上一个包级别。Three dots is up two levels, etc. 三点是上升两级,等等。So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. 所以如果你在pkg包中从某个模块执行from . import mod,然后您将最终导入pkg.modIf you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. 如果从pkg.subpkg1内部执行from ..subpkg2 import mod,您将导入pkg.subpkg2.modThe specification for relative imports is contained in the Package Relative Imports section.相对导入的规范包含在包相对导入部分中。

importlib.import_module() is provided to support applications that determine dynamically the modules to be loaded.用于支持动态确定要加载的模块的应用程序。

Raises an auditing event import with arguments module, filename, sys.path, sys.meta_path, sys.path_hooks.使用参数modulefilenamesys.pathsys.meta_pathsys.path_hooks引发审核事件import

7.11.1. Future statements未来语句

A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python where the feature becomes standard.未来语句是对编译器的一个指示,即特定模块应使用语法或语义进行编译,这些语法或语义将在Python的指定未来版本中提供,在该版本中,该功能将成为标准。

The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. future语句旨在简化到Python未来版本的迁移,这些版本会对语言进行不兼容的更改。It allows use of the new features on a per-module basis before the release in which the feature becomes standard.它允许在功能成为标准的版本之前,在每个模块的基础上使用新功能。


future_stmt ::= "from" "__future__" "import" feature ["as" identifier]
("," feature ["as" identifier])*
| "from" "__future__" "import" "(" feature ["as" identifier]
("," feature ["as" identifier])* [","] ")"
feature ::= identifier

A future statement must appear near the top of the module. future语句必须出现在模块顶部附近。The only lines that can appear before a future statement are:future语句之前只能显示以下行:

  • the module docstring (if any),模块docstring(如果有),

  • comments,评论,

  • blank lines, and空行,以及

  • other future statements.其他未来声明。

The only feature that requires using the future statement is annotations (see PEP 563).唯一需要使用未来语句的特性是annotations(请参见PEP 563)。

All historical features enabled by the future statement are still recognized by Python 3. Python 3仍然可以识别future语句启用的所有历史特性。The list includes absolute_import, division, generators, generator_stop, unicode_literals, print_function, nested_scopes and with_statement. 该列表包括absolute_importdivisiongeneratorsgenerator_stopunicode_literalsprint_functionnested_scopeswith_statementThey are all redundant because they are always enabled, and only kept for backwards compatibility.它们都是冗余的,因为它们始终处于启用状态,并且仅为向后兼容而保留。

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. future语句在编译时得到识别和特别处理:对核心构造语义的更改通常通过生成不同的代码来实现。It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. 甚至可能是新特性引入了新的不兼容语法(例如新的保留字),在这种情况下,编译器可能需要以不同的方式解析模块。Such decisions cannot be pushed off until runtime.这样的决定不能推迟到运行时。

For any given release, the compiler knows which feature names have been defined, and raises a compile-time error if a future statement contains a feature not known to it.对于任何给定的版本,编译器都知道定义了哪些功能名称,如果将来的语句包含未知的功能,则会引发编译时错误。

The direct runtime semantics are the same as for any import statement: there is a standard module __future__, described later, and it will be imported in the usual way at the time the future statement is executed.直接运行时语义与任何导入语句相同:有一个标准模块__future__在后面讲述,在执行未来的语句时,将以常规的方式导入它。

The interesting runtime semantics depend on the specific feature enabled by the future statement.有趣的运行时语义取决于future语句启用的特定功能。

Note that there is nothing special about the statement:请注意,该声明没有什么特别之处:

import __future__ [as name]

That is not a future statement; it’s an ordinary import statement with no special semantics or syntax restrictions.这不是未来的声明;这是一个普通的import语句,没有特殊的语义或语法限制。

Code compiled by calls to the built-in functions exec() and compile() that occur in a module M containing a future statement will, by default, use the new syntax or semantics associated with the future statement. 默认情况下,通过调用模块M中包含future语句的内置函数exec()compile()编译的代码将使用与future语句关联的新语法或语义。This can be controlled by optional arguments to compile() — see the documentation of that function for details.这可以由compile()的可选参数控制-有关详细信息,请参阅该函数的文档。

A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session. 在交互式口译员提示下键入的未来语句将在口译员会话的其余时间生效。If an interpreter is started with the -i option, is passed a script name to execute, and the script includes a future statement, it will be in effect in the interactive session started after the script is executed.如果使用-i选项启动解释器,并向其传递要执行的脚本名称,并且该脚本包含一个future语句,则该脚本将在脚本执行后启动的交互式会话中生效。

See also

PEP 236 - Back to the __future__

The original proposal for the __future__ mechanism.关于__future__机制的原始建议。

7.12. The global statementglobal语句


global_stmt ::= "global" identifier ("," identifier)*

The global statement is a declaration which holds for the entire current code block. global语句是一个声明,它适用于整个当前代码块。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,就不可能分配给全局变量,尽管自由变量可能引用全局变量而不声明为全局变量。

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 as targets in with statements or except clauses, or in a for target list, class definition, function definition, import statement, or variable annotation.global语句中列出的名称不能定义为形式参数,也不能定义为with语句或except子句中的目标,也不能定义为for目标列表、class定义、函数定义、import语句或变量注释中的目标。

CPython implementation detail:CPython实施详情: The current implementation does not enforce some of these 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:程序员备注: global is a directive to the parser. 是指向解析器的指令。It applies only to code parsed at the same time as the global statement. 它仅适用于与global语句同时解析的代码。In particular, a global statement contained in a string or code object supplied to the built-in exec() function does not affect the code block containing the function call, and code contained in such a string is unaffected by global statements in the code containing the function call. 特别是,提供给内置exec()函数的字符串或代码对象中包含的global语句不会影响包含函数调用的代码块,并且此类字符串中包含的代码不受包含函数调用的代码中的global语句的影响。The same applies to the eval() and compile() functions.这同样适用于eval()compile()函数。

7.13. The nonlocal statementnonlocal语句


nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. nonlocal语句使列出的标识符引用最近的封闭范围(不包括全局变量)中以前绑定的变量。This is important because the default behavior for binding is to search the local namespace first. 这很重要,因为绑定的默认行为是首先搜索本地名称空间。The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.该语句允许封装的代码将变量重新绑定到全局(模块)范围之外的局部范围之外。

Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).global语句中列出的名称不同,nonlocal语句中列出的名称必须引用封闭作用域中预先存在的绑定(创建新绑定的作用域无法明确确定)。

Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope.nonlocal语句中列出的名称不得与本地范围中预先存在的绑定冲突。

See also

PEP 3104 - Access to Names in Outer Scopes访问外部作用域中的名称

The specification for the nonlocal statement.nonlocal语句的规范。