8. 复合语句

Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line.

if , while and for statements implement traditional control flow constructs. try specifies exception handlers and/or cleanup code for a group of statements, while the with statement allows the execution of initialization and finalization code around a block of code. Function and class definitions are also syntactically compound statements.

A compound statement consists of one or more ‘clauses.’ A clause consists of a header and a ‘suite.’ The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of a suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which if clause a following else clause would belong:

if test1: if test2: print(x)
							

Also note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the print() calls are executed:

if x < y < z: print(x); print(y); print(z)
							

Summarizing:

compound_stmt ::=  if_stmt
                   | while_stmt
                   | for_stmt
                   | try_stmt
                   | with_stmt
                   | funcdef
                   | classdef
                   | async_with_stmt
                   | async_for_stmt
                   | async_funcdef
suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement     ::=  stmt_list NEWLINE | compound_stmt
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]
					

Note that statements always end in a NEWLINE possibly followed by a DEDENT . Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the ‘dangling else ’ problem is solved in Python by requiring nested if statements to be indented).

The formatting of the grammar rules in the following sections places each clause on a separate line for clarity.

8.1. if 语句

if 语句用于条件执行:

if_stmt ::=  "if" expression ":" suite
             ("elif" expression ":" suite)*
             ["else" ":" suite]
						

It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section 布尔运算 for the definition of true and false); then that suite is executed (and no other part of the if statement is executed or evaluated). If all expressions are false, the suite of the else clause, if present, is executed.

8.2. while 语句

while 语句用于重复执行只要表达式为 True:

while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]
						

这将反复测试表达式,若为 True,执行第一套件;若表达式为 False (可能是首次测试),执行套件 else 子句,若它存在,执行并循环终止。

break 语句在第一套件中执行将终止循环而不执行 else 子句套件。 continue 语句在第一套件中执行将跳过套件的其余部分并回到测试表达式。

8.3. for 语句

for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]
						

The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list . The suite is then executed once for each item provided by the iterator, in the order returned by the iterator. Each item in turn is assigned to the target list using the standard rules for assignments (see 赋值语句 ), and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty or an iterator raises a StopIteration exception), the suite in the else clause, if present, is executed, and the loop terminates.

break 语句在第一套件中执行将终止循环而不执行 else 子句套件。 continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there is no next item.

The for-loop makes assignments to the variables(s) in the target list. This overwrites all previous assignments to those variables including those made in the suite of the for-loop:

for i in range(10):
    print(i)
    i = 5             # this will not affect the for-loop
                      # because i will be overwritten with the next
                      # index in the range
								

Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop. Hint: the built-in function range() returns an iterator of integers suitable to emulate the effect of Pascal’s for i := a to b do ; e.g., list(range(3)) returns the list [0, 1, 2] .

注意

There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, e.g. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,

for x in a[:]:
    if x < 0: a.remove(x)
									

8.4. try 语句

try 语句为一组语句指定异常处理程序和/或清理代码:

try_stmt  ::=  try1_stmt | try2_stmt
try1_stmt ::=  "try" ":" suite
               ("except" [expression ["as" identifier]] ":" suite)+
               ["else" ":" suite]
               ["finally" ":" suite]
try2_stmt ::=  "try" ":" suite
               "finally" ":" suite
						

except clause(s) specify one or more exception handlers. When no exception occurs in the try clause, no exception handler is executed. When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object or a tuple containing an item compatible with the exception.

If no except clause matches the exception, the search for an exception handler continues in the surrounding code and on the invocation stack. [1]

If the evaluation of an expression in the header of an except clause raises an exception, the original search for a handler is canceled and a search starts for the new exception in the surrounding code and on the call stack (it is treated as if the entire try statement raised the exception).

When a matching except clause is found, the exception is assigned to the target specified after the as keyword in that except clause, if present, and the except clause’s suite is executed. All except clauses must have an executable block. When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.)

When an exception has been assigned using as target , it is cleared at the end of the except clause. This is as if

except E as N:
    foo
								

was translated to

except E as N:
    try:
        foo
    finally:
        del N
								

This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.

Before an except clause’s suite is executed, details about the exception are stored in the sys module and can be accessed via sys.exc_info() . sys.exc_info() returns a 3-tuple consisting of the exception class, the exception instance and a traceback object (see section 标准类型层次结构 ) identifying the point in the program where the exception occurred. sys.exc_info() values are restored to their previous values (before the call) when returning from a function that handled an exception.

可选 else 子句会被执行,若控制流离开 try suite, no exception was raised, and no return , continue ,或 break statement was executed. Exceptions in the else clause are not handled by the preceding except clauses.

finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception. If the finally clause executes a return or break statement, the saved exception is discarded:

>>> def f():
...     try:
...         1/0
...     finally:
...         return 42
...
>>> f()
42
								

The exception information is not available to the program during execution of the finally 子句。

return , break or continue statement is executed in the try suite of a try finally statement, the finally clause is also executed ‘on the way out.’ A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation — this restriction may be lifted in the future).

The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed:

>>> def foo():
...     try:
...         return 'try'
...     finally:
...         return 'finally'
...
>>> foo()
'finally'
								

Additional information on exceptions can be found in section 异常 , and information on using the raise statement to generate exceptions may be found in section raise 语句 .

8.5. with 语句

with statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers ). This allows common try except finally usage patterns to be encapsulated for convenient reuse.

with_stmt ::=  "with" with_item ("," with_item)* ":" suite
with_item ::=  expression ["as" target]
						

The execution of the with statement with one “item” proceeds as follows:

  1. The context expression (the expression given in the with_item ) is evaluated to obtain a context manager.

  2. The context manager’s __exit__() is loaded for later use.

  3. The context manager’s __enter__() method is invoked.

  4. If a target was included in the with statement, the return value from __enter__() is assigned to it.

    注意

    with statement guarantees that if the __enter__() method returns without an error, then __exit__() will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. See step 6 below.

  5. The suite is executed.

  6. The context manager’s __exit__() method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to __exit__() . Otherwise, three None arguments are supplied.

    If the suite was exited due to an exception, and the return value from the __exit__() method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the with 语句。

    If the suite was exited for any reason other than an exception, the return value from __exit__() is ignored, and execution proceeds at the normal location for the kind of exit that was taken.

With more than one item, the context managers are processed as if multiple with statements were nested:

with A() as a, B() as b:
    suite
								

相当于

with A() as a:
    with B() as b:
        suite
								

3.1 版改变: 支持多上下文表达式。

另请参阅

PEP 343 - with 语句
规范、背景及范例为 Python with 语句。

8.6. 函数定义

函数定义定义用户定义的函数对象 (见章节 标准类型层次结构 ):

funcdef                 ::=  [decorators] "def" funcname "(" [parameter_list] ")"
                             ["->" expression] ":" suite
decorators              ::=  decorator+
decorator               ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
dotted_name             ::=  identifier ("." identifier)*
parameter_list          ::=  defparameter ("," defparameter)* ["," [parameter_list_starargs]]
                             | parameter_list_starargs
parameter_list_starargs ::=  "*" [parameter] ("," defparameter)* ["," ["**" parameter [","]]]
                             | "**" parameter [","]
parameter               ::=  identifier [":" expression]
defparameter            ::=  parameter ["=" expression]
funcname                ::=  identifier
						

函数定义是可执行语句。它的执行将当前本地名称空间中的函数名称绑定到函数对象 (围绕函数可执行代码的包裹器)。此函数对象包含当前全局名称空间 (作为要使用的全局名称空间) 的引用,当函数被调用时。

函数定义不执行函数本体;这获得执行,仅当函数被调用时。 [2]

函数定义可以被包裹通过一个或多个 装饰器 表达式。评估装饰器表达式当定义函数时,在包含函数定义的作用域内。结果必须是可调用,它以函数对象作为唯一自变量被援引。返回值被绑定到函数名称,而不是函数对象。多个装饰器按嵌套方式应用。例如,以下代码

@f1(arg)
@f2
def func(): pass
								

大致相当于

def func(): pass
func = f1(arg)(f2(func))
								

除了原始函数不被临时绑定到名称 func .

When one or more 参数 have the form parameter = expression , the function is said to have “default parameter values.” For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter’s default value is substituted. If a parameter has a default value, all following parameters up until the “ * ” must also have a default value — this is a syntactic restriction that is not expressed by the grammar.

会从左到右评估默认参数值,当执行函数定义时。 This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin
								

Function call semantics are described in more detail in section 调用 . A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form “ *identifier ” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “ **identifier ” is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type. Parameters after “ * *identifier ” are keyword-only parameters and may only be passed used keyword arguments.

Parameters may have annotations of the form “ : expression ” following the parameter name. Any parameter may have an annotation even those of the form *identifier or **identifier . Functions may have “return” annotation of the form “ -> expression ” after the parameter list. These annotations can be any valid Python expression and are evaluated when the function definition is executed. Annotations may be evaluated in a different order than they appear in the source code. The presence of annotations does not change the semantics of a function. The annotation values are available as values of a dictionary keyed by the parameters’ names in the __annotations__ 属性为函数对象。

It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda expressions, described in section Lambdas . Note that the lambda expression is merely a shorthand for a simplified function definition; a function defined in a “ def ” statement can be passed around or assigned to another name just like a function defined by a lambda expression. The “ def ” form is actually more powerful since it allows the execution of multiple statements and annotations.

程序员注意: Functions are first-class objects. A “ def ” statement executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section 命名和绑定 了解细节。

另请参阅

PEP 3107 - 函数注解
函数注解的原始规范。

8.7. 类定义

类定义定义类对象 (见章节 标准类型层次结构 ):

classdef    ::=  [decorators] "class" classname [inheritance] ":" suite
inheritance ::=  "(" [argument_list] ")"
classname   ::=  identifier
						

A class definition is an executable statement. The inheritance list usually gives a list of base classes (see Metaclasses for more advanced uses), so each item in the list should evaluate to a class object which allows subclassing. Classes without an inheritance list inherit, by default, from the base class object ; hence,

class Foo:
    pass
								

相当于

class Foo(object):
    pass
								

The class’s suite is then executed in a new execution frame (see 命名和绑定 ), using a newly created local namespace and the original global namespace. (Usually, the suite contains mostly function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. [3] A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace.

The order in which attributes are defined in the class body is preserved in the new class’s __dict__ . Note that this is reliable only right after the class is created and only for classes that were defined using the definition syntax.

Class creation can be customized heavily using metaclasses .

Classes can also be decorated: just like when decorating functions,

@f1(arg)
@f2
class Foo: pass
								

大致相当于

class Foo: pass
Foo = f1(arg)(f2(Foo))
								

The evaluation rules for the decorator expressions are the same as for function decorators. The result is then bound to the class name.

程序员注意: Variables defined in the class definition are class attributes; they are shared by instances. Instance attributes can be set in a method with self.name = value . Both class and instance attributes are accessible through the notation “ self.name ”, and an instance attribute hides a class attribute with the same name when accessed in this way. Class attributes can be used as defaults for instance attributes, but using mutable values there can lead to unexpected results. Descriptors can be used to create instance variables with different implementation details.

另请参阅

PEP 3115 - Python 3000 中的元类
The proposal that changed the declaration of metaclasses to the current syntax, and the semantics for how classes with metaclasses are constructed.
PEP 3129 - 类装饰器
The proposal that added class decorators. Function and method decorators were introduced in PEP 318 .

8.8. 协程

3.5 版新增。

8.8.1. 协程函数定义

async_funcdef ::=  [decorators] "async" "def" funcname "(" [parameter_list] ")"
                   ["->" expression] ":" suite
							

可以在许多点挂起和再继续 Python 协程的执行 (见 协程 )。在协程本体内,任何 await and async 标识符变为预留关键词; await 表达式, async for and async with 只可用于协程本体内。

函数定义采用 async def 句法始终是协程函数,即使它们不包含 await or async 关键词。

它是 SyntaxError 要使用 yield from 表达式在 async def 协程。

协程函数范例:

async def func(param1, param2):
    do_stuff()
    await some_coroutine()
									

8.8.2. async for 语句

async_for_stmt ::=  "async" for_stmt
							

异步可迭代 能够调用异步代码在其 iter 实现,和 异步迭代器 可以调用异步代码在其 next 方法。

async for 语句允许方便迭代异步迭代器。

以下代码:

async for TARGET in ITER:
    BLOCK
else:
    BLOCK2
									

在语义上等效于:

iter = (ITER)
iter = type(iter).__aiter__(iter)
running = True
while running:
    try:
        TARGET = await type(iter).__anext__(iter)
    except StopAsyncIteration:
        running = False
    else:
        BLOCK
else:
    BLOCK2
									

另请参阅 __aiter__() and __anext__() 了解细节。

它是 SyntaxError 要使用 async for statement outside of an async def 函数。

8.8.3. async with 语句

async_with_stmt ::=  "async" with_stmt
							

An 异步上下文管理器 上下文管理器 that is able to suspend execution in its enter and exit 方法。

以下代码:

async with EXPR as VAR:
    BLOCK
									

在语义上等效于:

mgr = (EXPR)
aexit = type(mgr).__aexit__
aenter = type(mgr).__aenter__(mgr)
VAR = await aenter
try:
    BLOCK
except:
    if not await aexit(mgr, *sys.exc_info()):
        raise
else:
    await aexit(mgr, None, None, None)
									

另请参阅 __aenter__() and __aexit__() 了解细节。

它是 SyntaxError 要使用 async with statement outside of an async def 函数。

另请参阅

PEP 492 具有 async 和 await 句法的协程
使协程成为 Python 中的适当独立概念,并添加了支持句法的提案。

脚注

[1] The exception is propagated to the invocation stack unless there is a finally clause which happens to raise another exception. That new exception causes the old one to be lost.
[2] A string literal appearing as the first statement in the function body is transformed into the function’s __doc__ attribute and therefore the function’s docstring .
[3] A string literal appearing as the first statement in the class body is transformed into the namespace’s __doc__ item and therefore the class’s docstring .