8. Compound statements复合语句¶
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.一般来说,复合语句跨越多行,尽管在简单的情况下,一个完整的复合语句可能包含在一行中。
The if
, while
and for
statements implement traditional control flow constructs. if
、while
和for
语句实现了传统的控制流结构。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. try
为一组语句指定异常处理程序和/或清理代码,而with
语句允许围绕一块代码执行初始化和终结代码。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.’ 子句由标题和“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:else
子句属于哪一条if
子句:
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:print()
调用,要么不执行任何print()
调用:
if x < y < z: print(x); print(y); print(z)
Summarizing:总结:
compound_stmt ::=if_stmt
|while_stmt
|for_stmt
|try_stmt
|with_stmt
|match_stmt
|funcdef
|classdef
|async_with_stmt
|async_for_stmt
|async_funcdef
suite ::=stmt_list
NEWLINE | NEWLINE INDENTstatement
+ 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
. NEWLINE
结尾,后面可能跟一个DEDENT
。Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the ‘dangling 还要注意的是,可选的continuation子句总是以一个不能启动语句的关键字开头,因此没有歧义(在Python中,通过要求嵌套的else
’ problem is solved in Python by requiring nested if
statements to be indented).if
语句缩进来解决“悬空else
”问题)。
The formatting of the grammar rules in the following sections places each clause on a separate line for clarity.为了清晰起见,以下章节中语法规则的格式将每个子句放在单独的一行。
8.1. The if
statementif
语句¶
if
statementThe if
statement is used for conditional execution:if
语句用于条件执行:
if_stmt ::= "if"assignment_expression
":"suite
("elif"assignment_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 Boolean operations 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
语句的其他部分)。If all expressions are false, the suite of the 如果所有表达式都为else
clause, if present, is executed.false
,则执行else
子句套件(如果存在)。
8.2. The while
statementwhile
语句¶
while
statementThe while
statement is used for repeated execution as long as an expression is true:while
语句用于重复执行,只要表达式为true
:
while_stmt ::= "while"assignment_expression
":"suite
["else" ":"suite
]
This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the 这会重复测试表达式,如果是真的,则执行第一个套件;如果表达式为else
clause, if present, is executed and the loop terminates.false
(可能是第一次测试),则执行else
子句套件(如果存在),循环终止。
A 在第一个套件中执行的break
statement executed in the first suite terminates the loop without executing the else
clause’s suite. break
语句终止循环,而不执行else
子句的套件。A 在第一个套件中执行的continue
statement executed in the first suite skips the rest of the suite and goes back to testing the expression.continue
语句跳过套件的其余部分,并返回测试表达式。
8.3. The for
statementfor
语句¶
for
statementThe for
statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:for
语句用于迭代序列(如字符串、元组或列表)或其他可迭代对象的元素:
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
. 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 Assignment statements), 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.StopIteration
异常时),执行else
子句中的套件(如果存在),循环终止。
A 在第一个套件中执行的break
statement executed in the first suite terminates the loop without executing the else
clause’s suite. break
语句终止循环,而不执行else
子句的套件。A 在第一个套件中执行的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.continue
语句跳过套件的其余部分并继续执行下一项,如果没有下一项,则继续执行else
子句。
The for-loop makes assignments to the variables in the target list. for循环对目标列表中的变量进行赋值。This overwrites all previous assignments to those variables including those made in the suite of the for-loop:这将覆盖以前对这些变量的所有赋值,包括在for循环套件中进行的赋值:
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]
.range()
返回一个整数迭代器,该迭代器适合模拟Pascal的for i := a to b do
的影响;例如,list(range(3))
返回列表[0, 1, 2]
。
8.4. The try
statementtry
语句¶
try
statementThe try
statement specifies exception handlers and/or cleanup code for a group of statements: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
The except
clause(s) specify one or more exception handlers. except
子句指定一个或多个异常处理程序。When no exception occurs in the 如果try
clause, no exception handler is executed. try
子句中没有发生异常,则不会执行异常处理程序。When an exception occurs in the 当try
suite, a search for an exception handler is started. try
套件中发生异常时,将开始搜索异常处理程序。This search inspects the except clauses in turn until one is found that matches the exception. 此搜索将依次检查except
子句,直到找到与异常匹配的子句。An expression-less except clause, if present, must be last; it matches any exception. 缺少表达式的except
子句(如果存在)必须是最后一个;它匹配任何异常。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. 对于带有表达式的except
子句,将计算该表达式,如果生成的对象与异常“兼容”,则该子句与异常匹配。An object is compatible with an exception if the object is the class or a non-virtual base class of the exception object, or a tuple containing an item that is the class or a non-virtual base class of the exception object.如果对象是异常对象的类或非虚拟基类,或包含异常对象的类或非虚拟基类的项的元组,则该对象与异常兼容。
If no except clause matches the exception, the search for an exception handler continues in the surrounding code and on the invocation stack. 如果没有与异常匹配的except
子句,则在周围的代码和调用堆栈中继续搜索异常处理程序。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).except
子句标头中的表达式求值引发异常,则取消对处理程序的原始搜索,并开始在周围代码和调用堆栈中搜索新异常(视为整个try
语句引发异常)。
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. except
子句时,将异常分配给该except
子句中as
关键字之后指定的目标(如果存在),并执行except
子句的套件。All except clauses must have an executable block. 所有except
子句都必须具有可执行块。When the end of this block is reached, execution continues normally after the entire try statement. 当到达此块的末尾时,在整个try语句之后,执行将正常继续。(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.)(这意味着,如果同一异常存在两个嵌套处理程序,并且该异常发生在内部处理程序的try子句中,则外部处理程序将不会处理该异常。)
When an exception has been assigned using 使用as target
, it is cleared at the end of the except clause. as target
分配异常后,将在except子句末尾清除该异常。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. 这意味着必须将异常指定给其他名称,才能在except
子句之后引用它。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()
. except
子句的套件之前,有关异常的详细信息存储在sys
模块中,可以通过sys.exc_info()
访问。sys.exc_info()
returns a 3-tuple consisting of the exception class, the exception instance and a traceback object (see section The standard type hierarchy) identifying the point in the program where the exception occurred. 返回一个三元组,由异常类、异常实例和回溯对象(请参阅标准类型层次结构一节)组成,用于标识程序中发生异常的点。The details about the exception accessed via 离开异常处理程序时,有关通过sys.exc_info()
are restored to their previous values when leaving an exception handler:sys.exc_info()
访问的异常的详细信息将恢复为以前的值:
>>> print(sys.exc_info())
(None, None, None)
>>> try:
... raise TypeError
... except:
... print(sys.exc_info())
... try:
... raise ValueError
... except:
... print(sys.exc_info())
... print(sys.exc_info())
...
(<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>)
(<class 'ValueError'>, ValueError(), <traceback object at 0x10efad040>)
(<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>)
>>> print(sys.exc_info())
(None, None, None)
The optional 如果控制流离开else
clause is executed if the control flow leaves the try
suite, no exception was raised, and no return
, continue
, or break
statement was executed. try
套件,没有引发异常,并且没有执行return
、continue
或break
语句,则会执行可选的else
子句。Exceptions in the else
clause are not handled by the preceding except
clauses.else
子句中的例外情况不由上述except
条款处理。
If 如果finally
is present, it specifies a ‘cleanup’ handler. finally
存在,则指定“清理”处理程序。The 执行try
clause is executed, including any except
and else
clauses. try
子句,包括任何except
和else
子句。If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. 如果任何子句中发生异常且未处理,则会临时保存该异常。The 执行finally
clause is executed. finally
子句。If there is a saved exception it is re-raised at the end of the 如果存在保存的异常,将在finally
clause. finally
子句末尾重新引发该异常。If the 如果finally
clause raises another exception, the saved exception is set as the context of the new exception. finally
子句引发另一个异常,则将保存的异常设置为新异常的上下文。If the 如果finally
clause executes a return
, break
or continue
statement, the saved exception is discarded:finally
子句执行return
、break
或continue
语句,则丢弃保存的异常:
>>> def f():
... try:
... 1/0
... finally:
... return 42
...
>>> f()
42
The exception information is not available to the program during execution of the 在执行finally
clause.finally
子句期间,程序无法获得异常信息。
When a 当在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.’try
…finally
语句的try
套件中执行return
、break
或continue
语句时,finally
子句也会“在退出时”执行
The return value of a function is determined by the last 函数的返回值由最后执行的return
statement executed. return
语句确定。Since the 由于finally
clause always executes, a return
statement executed in the finally
clause will always be the last one executed:finally
子句始终执行,因此finally
子句中执行的return
语句将始终是最后执行的语句:
>>> def foo():
... try:
... return 'try'
... finally:
... return 'finally'
...
>>> foo()
'finally'
Additional information on exceptions can be found in section Exceptions, and information on using the 有关异常的其他信息可以在异常部分中找到,有关使用raise
statement to generate exceptions may be found in section The raise statement.raise
语句生成异常的信息可以在raise
语句部分中找到。
8.5. The with
statementwith
语句¶
with
statementThe with
statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). with
语句用于使用上下文管理器定义的方法包装块的执行(请参阅with
语句上下文管理器一节)。This allows common 这允许封装常见的try
…except
…finally
usage patterns to be encapsulated for convenient reuse.try
…except
…finally
使用模式,以便于重用。
with_stmt ::= "with" ( "("with_stmt_contents
","? ")" |with_stmt_contents
) ":"suite
with_stmt_contents ::=with_item
(","with_item
)*
with_item ::=expression
["as"target
]
The execution of the 使用一个“item”执行with
statement with one “item” proceeds as follows:with
语句的过程如下:
The context expression (the expression given in the对上下文表达式(with_item
) is evaluated to obtain a context manager.with_item
中给出的表达式)进行求值以获得上下文管理器。The context manager’s将加载上下文管理器的__enter__()
is loaded for later use.__enter__()
,以供以后使用。The context manager’s将加载上下文管理器的__exit__()
is loaded for later use.__exit__()
以供以后使用。The context manager’s将调用上下文管理器的__enter__()
method is invoked.__enter__()
方法。If a target was included in the如果with
statement, the return value from__enter__()
is assigned to it.with
语句中包含目标,则会为其分配来自__enter__()
的返回值。Note
Thewith
statement guarantees that if the__enter__()
method returns without an error, then__exit__()
will always be called.with
语句保证,如果返回的__enter__()
方法没有错误,那么将始终调用__exit__()
方法。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.请参阅下面的步骤6。The suite is executed.该套件已执行。The context manager’s将调用上下文管理器的__exit__()
method is invoked.__exit__()
方法。If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to如果异常导致套件退出,则其类型、值和回溯将作为参数传递给__exit__()
.__exit__()
。Otherwise, three否则,将提供三个None
arguments are supplied.None
参数。If the suite was exited due to an exception, and the return value from the如果套件因异常而退出,并且__exit__()
method was false, the exception is reraised.__exit__()
方法的返回值为false
,则会重新引发异常。If the return value was true, the exception is suppressed, and execution continues with the statement following the如果返回值为with
statement.true
,则会抑制异常,并继续执行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.__exit__()
的返回值,并在所采取的退出类型的正常位置继续执行。
The following code:以下代码:
with EXPRESSION as TARGET:
SUITE
is semantically equivalent to:在语义上等同于:
manager = (EXPRESSION)
enter = type(manager).__enter__
exit = type(manager).__exit__
value = enter(manager)
hit_except = False
try:
TARGET = value
SUITE
except:
hit_except = True
if not exit(manager, *sys.exc_info()):
raise
finally:
if not hit_except:
exit(manager, None, None, None)
With more than one item, the context managers are processed as if multiple 对于多个项,上下文管理器的处理就像嵌套了多个with
statements were nested:with
语句一样:
with A() as a, B() as b:
SUITE
is semantically equivalent to:在语义上等同于:
with A() as a:
with B() as b:
SUITE
You can also write multi-item context managers in multiple lines if the items are surrounded by parentheses. 如果项目被括号包围,您还可以在多行中编写多项目上下文管理器。For example:例如:
with (
A() as a,
B() as b,
):
SUITE
Changed in version 3.1:版本3.1中更改: Support for multiple context expressions.支持多个上下文表达式。
Changed in version 3.10:版本3.10中更改: Support for using grouping parentheses to break the statement in multiple lines.支持使用分组括号将语句分隔为多行。
8.6. The match
statementmatch
语句¶
match
statementNew in version 3.10.版本3.10中新增。
The match statement is used for pattern matching. match语句用于模式匹配。Syntax:语法:
match_stmt ::= 'match'subject_expr
":" NEWLINE INDENTcase_block
+ DEDENT
subject_expr ::=star_named_expression
","star_named_expressions
?
|named_expression
case_block ::= 'case'patterns
[guard
] ":"block
Note
This section uses single quotes to denote soft keywords.本节使用单引号表示软关键字。
Pattern matching takes a pattern as input (following 模式匹配将模式作为输入(跟着case
) and a subject value (following match
). case
)和主题值(跟着match
)。The pattern (which may contain subpatterns) is matched against the subject value. 模式(可能包含子模式)与主题值匹配。The outcomes are:结果是:
A match success or failure (also termed a pattern success or failure).匹配的成功或失败(也称为模式成功或失败)。Possible binding of matched values to a name.匹配值可能绑定到名称。The prerequisites for this are further discussed below.下面将进一步讨论这方面的先决条件。
The match
and case
keywords are soft keywords.match
关键字和case
关键字是软关键字。
See also
8.6.1. Overview概述¶
Here’s an overview of the logical flow of a match statement:下面是match语句逻辑流的概述:
The subject expression对主题表达式subject_expr
is evaluated and a resulting subject value obtained.subject_expr
进行求值,并获得结果subject值。If the subject expression contains a comma, a tuple is constructed using the standard rules.如果主题表达式包含逗号,则使用标准规则构造元组。Each pattern in acase_block
is attempted to match with the subject value.case_block
中的每个图案都试图与主题值匹配。The specific rules for success or failure are described below.成功或失败的具体规则如下所述。The match attempt can also bind some or all of the standalone names within the pattern.匹配尝试还可以绑定模式中的部分或所有独立名称。The precise pattern binding rules vary per pattern type and are specified below.精确的模式绑定规则因模式类型而异,如下所述。Name bindings made during a successful pattern match outlive the executed block and can be used after the match statement.在成功的模式匹配期间进行的名称绑定比执行的块更有效,并且可以在match语句之后使用。Note
During failed pattern matches, some subpatterns may succeed.在失败的模式匹配期间,某些子模式可能会成功。Do not rely on bindings being made for a failed match.不要依赖为失败的匹配所做的绑定。Conversely, do not rely on variables remaining unchanged after a failed match.相反,不要依赖匹配失败后保持不变的变量。The exact behavior is dependent on implementation and may vary.具体行为取决于实现,可能会有所不同。This is an intentional decision made to allow different implementations to add optimizations.这是一个有意的决定,允许不同的实现添加优化。If the pattern succeeds, the corresponding guard (if present) is evaluated.如果模式成功,将评估相应的保护(如果存在)。In this case all name bindings are guaranteed to have happened.在这种情况下,保证所有名称绑定都已发生。If the guard evaluates as true or is missing, the如果guard的计算结果为block
insidecase_block
is executed.true
或缺失,则执行case_block
中的块。Otherwise, the next否则,如上所述尝试下一个case_block
is attempted as described above.case_block
。If there are no further case blocks, the match statement is completed.如果没有其他case
块,则完成match
语句。
Note
Users should generally never rely on a pattern being evaluated. 用户通常不应该依赖于正在评估的模式。Depending on implementation, the interpreter may cache values or use other optimizations which skip repeated evaluations.根据实现的不同,解释器可以缓存值或使用跳过重复计算的其他优化。
A sample match statement:匹配语句示例:
>>> flag = False
>>> match (100, 200):
... case (100, 300): # Mismatch: 200 != 300
... print('Case 1')
... case (100, 200) if flag: # Successful match, but guard fails
... print('Case 2')
... case (100, y): # Matches and binds y to 200
... print(f'Case 3, y: {y}')
... case _: # Pattern not attempted
... print('Case 4, I match anything!')
...
Case 3, y: 200
In this case, 在这种情况下,if flag
is a guard. if
标志是一个护卫。Read more about that in the next section.请在下一节中阅读更多相关内容。
8.6.2. Guards护卫¶
guard ::= "if"named_expression
A 护卫guard
(which is part of the case
) must succeed for code inside the case
block to execute. guard
(属于case
的一部分)必须成功,才能执行case
块内的代码。It takes the form: 其形式为:if
followed by an expression.if
后跟表达式。
The logical flow of a 具有护卫的case
block with a guard
follows:case
块的逻辑流如下所示:
Check that the pattern in the检查case
block succeeded.case
块中的模式是否成功。If the pattern failed, the如果模式失败,则不评估护卫,并检查下一个guard
is not evaluated and the nextcase
block is checked.case
块。If the pattern succeeded, evaluate the如果模式成功,请评估护卫。guard
.If the如果guard
condition evaluates as true, the case block is selected.guard
条件的评估结果为真,则选择case
块。If the如果guard
condition evaluates as false, the case block is not selected.guard
条件评估为false
,则不会选择case
块。If the如果guard
raises an exception during evaluation, the exception bubbles up.guard
在评估期间引发异常,则会出现异常。
Guards are allowed to have side effects as they are expressions. 警卫被允许有副作用,因为他们是表达。Guard evaluation must proceed from the first to the last case block, one at a time, skipping case blocks whose pattern(s) don’t all succeed. 守卫评估必须从第一个案例块开始到最后一个案例块,一次一个,跳过模式不完全成功的案例块。(I.e., guard evaluation must happen in order.) (即,必须按顺序进行防护评估。)Guard evaluation must stop once a case block is selected.选择案例块后,必须停止防护评估。
8.6.3. Irrefutable Case Blocks无可辩驳的case
块¶
An irrefutable case block is a match-all case block. 无可辩驳的案例块是匹配所有案例块。A match statement may have at most one irrefutable case block, and it must be last.match
语句最多只能有一个无可辩驳的case
块,并且必须是最后一个。
A case block is considered irrefutable if it has no guard and its pattern is irrefutable. 如果一个case
块没有护卫装置,并且其模式是无可辩驳的,那么它就被认为是无可辩驳的。A pattern is considered irrefutable if we can prove from its syntax alone that it will always succeed. 如果我们仅从其语法就可以证明它总是成功的,那么模式被认为是无可辩驳的。Only the following patterns are irrefutable:只有以下模式是无可辩驳的:
AS
Patterns模式whose left-hand side is irrefutable他的左手边是无可辩驳的OR
Patterns模式containing at least one irrefutable pattern至少包含一种无可辩驳的模式parenthesized irrefutable patterns带圆括号的无可辩驳模式
8.6.4. Patterns模式¶
Note
This section uses grammar notations beyond standard EBNF:本节使用标准EBNF以外的语法符号:
the notation符号SEP.RULE+
is shorthand forRULE (SEP RULE)*
SEP.RULE+
是RULE (SEP RULE)*
的简写形式the notation符号!RULE
is shorthand for a negative lookahead assertion!RULE
是消极前瞻断言的简写形式
The top-level syntax for patterns
is:patterns
的顶级语法是:
patterns ::=open_sequence_pattern
|pattern
pattern ::=as_pattern
|or_pattern
closed_pattern ::= |literal_pattern
|capture_pattern
|wildcard_pattern
|value_pattern
|group_pattern
|sequence_pattern
|mapping_pattern
|class_pattern
The descriptions below will include a description “in simple terms” of what a pattern does for illustration purposes (credits to Raymond Hettinger for a document that inspired most of the descriptions). 下面的描述将包括“用简单的术语”描述一个模式的作用,以便于演示(雷蒙德·赫廷格的一篇文档激发了大部分描述的灵感)。Note that these descriptions are purely for illustration purposes and may not reflect the underlying implementation. 请注意,这些描述仅用于说明目的,可能不反映底层实现。Furthermore, they do not cover all valid forms.此外,它们并不涵盖所有有效的表格。
8.6.4.1. OR Patterns模式¶
An OR pattern is two or more patterns separated by vertical bars OR模式是由竖条|
. |
分隔的两个或多个模式。Syntax:语法:
or_pattern ::= "|".closed_pattern
+
Only the final subpattern may be irrefutable, and each subpattern must bind the same set of names to avoid ambiguity.只有最后的子模式可能是无可辩驳的,每个子模式必须绑定相同的名称集以避免歧义。
An OR pattern matches each of its subpatterns in turn to the subject value, until one succeeds. OR模式将其每个子模式依次与主题值匹配,直到其中一个成功。The OR pattern is then considered successful. 然后,OR模式被认为是成功的。Otherwise, if none of the subpatterns succeed, the OR pattern fails.否则,如果没有任何子模式成功,则OR模式将失败。
In simple terms, 简单地说,P1 | P2 | ...
will try to match P1
, if it fails it will try to match P2
, succeeding immediately if any succeeds, failing otherwise.P1 | P2 | ...
将尝试匹配P1
,如果失败,将尝试匹配P2
,如果成功,将立即成功,否则将失败。
8.6.4.2. AS Patterns模式¶
An AS pattern matches an OR pattern on the left of the AS模式将as
keyword against a subject. as
关键字左侧的OR模式与主题匹配。Syntax:语法:
as_pattern ::=or_pattern
"as"capture_pattern
If the OR pattern fails, the AS pattern fails. 如果OR模式失败,则AS模式失败。Otherwise, the AS pattern binds the subject to the name on the right of the as keyword and succeeds. 否则,AS模式将主题绑定到AS关键字右侧的名称,并成功。capture_pattern
cannot be a a 不能是_
._
。
In simple terms 简单地说,P as NAME
will match with P
, and on success it will set NAME = <subject>
.P as NAME
将与P
匹配,如果成功,它将设置NAME=<subject>
。
8.6.4.3. Literal Patterns文字模式¶
A literal pattern corresponds to most literals in Python. 文字模式对应于Python中的大多数文字。Syntax:语法:
literal_pattern ::=signed_number
|signed_number
"+" NUMBER
|signed_number
"-" NUMBER
|strings
| "None"
| "True"
| "False"
|signed_number
: NUMBER | "-" NUMBER
The rule 规则strings
and the token NUMBER
are defined in the standard Python grammar. strings
和口令NUMBER
在标准Python语法中定义。Triple-quoted strings are supported. 支持三引号字符串。Raw strings and byte strings are supported. 支持原始字符串和字节字符串。Formatted string literals are not supported.不支持格式化的字符串文字。
The forms signed_number '+' NUMBER
and signed_number '-' NUMBER
are for expressing complex numbers; they require a real number on the left and an imaginary number on the right. signed_number '+' NUMBER
和signed_number '-' NUMBER
的形式用于表示复数;它们需要在左边有一个实数,在右边有一个虚数。E.g. 例如:3 + 4j
.3 + 4j
。
In simple terms, 简单地说,只有当LITERAL
will succeed only if <subject> == LITERAL
. <subject> == LITERAL
时,LITERAL
才会成功。For the singletons 对于单例None
, True
and False
, the is
operator is used.None
,True
和False
,使用is
运算符。
8.6.4.4. Capture Patterns捕获模式¶
A capture pattern binds the subject value to a name. 捕获模式将主题值绑定到名称。Syntax:语法:
capture_pattern ::= !'_' NAME
A single underscore 单下划线_
is not a capture pattern (this is what !'_'
expresses). _
不是捕获模式(这是!'_'
所表达的)。It is instead treated as a 相反,它被视为wildcard_pattern
.wildcard_pattern
。
In a given pattern, a given name can only be bound once. 在给定的模式中,给定的名称只能绑定一次。E.g. 例如,当允许使用case x, x: ...
is invalid while case [x] | x: ...
is allowed.case [x] | x: ...
时,case x, x: ...
是无效的。
Capture patterns always succeed. 捕获模式总是成功的。The binding follows scoping rules established by the assignment expression operator in PEP 572; the name becomes a local variable in the closest containing function scope unless there’s an applicable 绑定遵循PEP 572中赋值表达式运算符建立的范围规则;除非有适用的global
or nonlocal
statement.global
或nonlocal
语句,否则名称将成为最近包含函数作用域中的局部变量。
In simple terms 简单来说,NAME
will always succeed and it will set NAME = <subject>
.NAME
总是成功的,它将设置NAME = <subject>
。
8.6.4.5. Wildcard Patterns通配符模式¶
A wildcard pattern always succeeds (matches anything) and binds no name. 通配符模式总是成功(匹配任何内容),并且不绑定任何名称。Syntax:语法:
wildcard_pattern ::= '_'
_
is a soft keyword within any pattern, but only within patterns. _
是任何模式中的软关键字,但仅在模式中。It is an identifier, as usual, even within 与往常一样,它是一个标识符,即使在match
subject expressions, guard
s, and case
blocks.match
主题表达式、guard
和case
块中也是如此。
In simple terms, 简单地说,_
will always succeed._
将永远成功。
8.6.4.6. Value Patterns值模式¶
A value pattern represents a named value in Python. 值模式表示Python中的命名值。Syntax:语法:
value_pattern ::=attr
attr ::=name_or_attr
"." NAME
name_or_attr ::=attr
| NAME
The dotted name in the pattern is looked up using standard Python name resolution rules. 使用标准Python名称解析规则查找模式中的虚线名称。The pattern succeeds if the value found compares equal to the subject value (using the 如果找到的值与主题值比较相等(使用==
equality operator).==
相等运算符),则模式成功。
In simple terms 简单地说,只有当NAME1.NAME2
will succeed only if <subject> == NAME1.NAME2
<subject> == NAME1.NAME2
时,NAME1.NAME2
才会成功
Note
If the same value occurs multiple times in the same match statement, the interpreter may cache the first value found and reuse it rather than repeat the same lookup. 如果同一个值在同一个match语句中多次出现,解释器可能会缓存找到的第一个值并重用它,而不是重复相同的查找。This cache is strictly tied to a given execution of a given match statement.此缓存严格绑定到给定匹配语句的给定执行。
8.6.4.7. Group Patterns组模式¶
A group pattern allows users to add parentheses around patterns to emphasize the intended grouping. 组模式允许用户在模式周围添加括号,以强调预期的分组。Otherwise, it has no additional syntax. 否则,它没有其他语法。Syntax:语法:
group_pattern ::= "(" pattern
")"
In simple terms 简单地说,(P)
has the same effect as P
.(P)
与P
具有相同的效果。
8.6.4.8. Sequence Patterns序列模式¶
A sequence pattern contains several subpatterns to be matched against sequence elements. 序列模式包含多个子模式,这些子模式与序列元素相匹配。The syntax is similar to the unpacking of a list or tuple.语法类似于列表或元组的解包。
sequence_pattern ::= "[" [maybe_sequence_pattern
] "]"
| "(" [open_sequence_pattern
] ")"
open_sequence_pattern ::=maybe_star_pattern
"," [maybe_sequence_pattern
]
maybe_sequence_pattern ::= ",".maybe_star_pattern
+ ","?
maybe_star_pattern ::=star_pattern
|pattern
star_pattern ::= "*" (capture_pattern
|wildcard_pattern
)
There is no difference if parentheses or square brackets are used for sequence patterns (i.e. 如果序列模式使用括号或方括号,则没有区别(即(...)
vs [...]
).(...)
vs [...]
)。
Note
A single pattern enclosed in parentheses without a trailing comma (e.g. 用括号括起来但不带尾随逗号的单个模式(例如(3 | 4)
) is a group pattern. (3 | 4)
)是一种组模式。While a single pattern enclosed in square brackets (e.g. 而方括号内的单一模式(如[3 | 4]
) is still a sequence pattern.[3 | 4]
)仍然是序列模式。
At most one star subpattern may be in a sequence pattern. 序列模式中最多可以有一个星形子模式。The star subpattern may occur in any position. 星形子模式可能出现在任何位置。If no star subpattern is present, the sequence pattern is a fixed-length sequence pattern; otherwise it is a variable-length sequence pattern.如果不存在星形子模式,则序列模式是固定长度的序列模式;否则,它是一个可变长度的序列模式。
The following is the logical flow for matching a sequence pattern against a subject value:以下是将序列模式与主题值匹配的逻辑流程:
If the subject value is not a sequence 2, the sequence pattern fails.如果主题值不是序列2,则序列模式失败。If the subject value is an instance of如果主题值是str
,bytes
orbytearray
the sequence pattern fails.str
、bytes
或bytearray
的实例,则序列模式将失败。The subsequent steps depend on whether the sequence pattern is fixed or variable-length.后续步骤取决于序列模式是固定长度还是可变长度。If the sequence pattern is fixed-length:如果序列模式为固定长度:If the length of the subject sequence is not equal to the number of subpatterns, the sequence pattern fails如果主题序列的长度不等于子模式的数量,则序列模式失败Subpatterns in the sequence pattern are matched to their corresponding items in the subject sequence from left to right.序列模式中的子模式与主题序列中的相应项目从左到右匹配。Matching stops as soon as a subpattern fails.一旦子模式失败,匹配就会停止。If all subpatterns succeed in matching their corresponding item, the sequence pattern succeeds.如果所有子模式都成功匹配其对应的项,则序列模式成功。
Otherwise, if the sequence pattern is variable-length:否则,如果序列模式为可变长度:If the length of the subject sequence is less than the number of non-star subpatterns, the sequence pattern fails.如果主题序列的长度小于非星形子模式的数量,则序列模式失败。The leading non-star subpatterns are matched to their corresponding items as for fixed-length sequences.对于固定长度序列,前导的非星形子模式与其对应的项相匹配。If the previous step succeeds, the star subpattern matches a list formed of the remaining subject items, excluding the remaining items corresponding to non-star subpatterns following the star subpattern.如果上一步成功,则星形子模式匹配由剩余主题项组成的列表,不包括与星形子模式之后的非星形子模式相对应的剩余项。Remaining non-star subpatterns are matched to their corresponding subject items, as for a fixed-length sequence.剩余的非星形子模式与其对应的主题项相匹配,就像固定长度的序列一样。
Note
The length of the subject sequence is obtained via主题序列的长度是通过len()
(i.e. via the__len__()
protocol).len()
获得的(即通过__len__()
协议)。This length may be cached by the interpreter in a similar manner as value patterns.解释器可以用与值模式类似的方式缓存该长度。
In simple terms 简单地说,[P1, P2, P3,
… , P<N>]
matches only if all the following happens:[P1, P2, P3, ... , P<N>]
仅在以下所有情况下匹配:
check检查<subject>
is a sequence<subject>
是一个序列len(subject) == <N>
P1
matches匹配<subject>[0]
(note that this match can also bind names)(请注意,此匹配也可以绑定名称)P2
matches匹配<subject>[1]
(note that this match can also bind names)(请注意,此匹配也可以绑定名称)…
and so on for the corresponding pattern/element.对于相应的模式/元素,依此类推。
8.6.4.9. Mapping Patterns映射模式¶
A mapping pattern contains one or more key-value patterns. 映射模式包含一个或多个键值模式。The syntax is similar to the construction of a dictionary. 语法类似于词典的构造。Syntax:语法:
mapping_pattern ::= "{" [items_pattern
] "}"
items_pattern ::= ",".key_value_pattern
+ ","?
key_value_pattern ::= (literal_pattern
|value_pattern
) ":"pattern
|double_star_pattern
double_star_pattern ::= "**"capture_pattern
At most one double star pattern may be in a mapping pattern. 映射模式中最多可以有一个双星模式。The double star pattern must be the last subpattern in the mapping pattern.双星模式必须是映射模式中的最后一个子模式。
Duplicate keys in mapping patterns are disallowed. 映射模式中不允许存在重复键。Duplicate literal keys will raise a 重复的文本键将引发SyntaxError
. SyntaxError
。Two keys that otherwise have the same value will raise a 否则具有相同值的两个键将在运行时引发ValueError
at runtime.ValueError
。
The following is the logical flow for matching a mapping pattern against a subject value:以下是将映射模式与主题值匹配的逻辑流程:
If the subject value is not a mapping 3,the mapping pattern fails.如果主题值不是映射3,则映射模式失败。If every key given in the mapping pattern is present in the subject mapping, and the pattern for each key matches the corresponding item of the subject mapping, the mapping pattern succeeds.如果映射模式中给定的每个键都存在于主题映射中,并且每个键的模式与主题映射的相应项匹配,则映射模式成功。If duplicate keys are detected in the mapping pattern, the pattern is considered invalid.如果在映射模式中检测到重复的密钥,则该模式被视为无效。A对于重复的文字值,会引发SyntaxError
is raised for duplicate literal values; or aValueError
for named keys of the same value.SyntaxError
;或具有相同值的命名键的ValueError
。
Note
Key-value pairs are matched using the two-argument form of the mapping subject’s 使用映射主题的get()
method. get()
方法的两个参数形式匹配键值对。Matched key-value pairs must already be present in the mapping, and not created on-the-fly via 匹配的键值对必须已经存在于映射中,并且不能通过__missing__()
or __getitem__()
.__missing__()
或__getitem__()
动态创建。
In simple terms 简单来说{KEY1: P1, KEY2: P2, ... }
matches only if all the following happens:{KEY1: P1, KEY2: P2, ... }
仅当发生以下所有情况时匹配:
check检查<subject>
is a mapping<subject>
是否为映射KEY1 in <subject>
P1
matches比赛<subject>[KEY1]
…
and so on for the corresponding KEY/pattern pair.对于相应的键/模式对,依此类推。
8.6.4.10. Class Patterns类模式¶
A class pattern represents a class and its positional and keyword arguments (if any). 类模式表示类及其位置参数和关键字参数(如果有)。Syntax:语法:
class_pattern ::=name_or_attr
"(" [pattern_arguments
","?] ")"
pattern_arguments ::=positional_patterns
[","keyword_patterns
]
|keyword_patterns
positional_patterns ::= ",".pattern
+
keyword_patterns ::= ",".keyword_pattern
+
keyword_pattern ::= NAME "="pattern
The same keyword should not be repeated in class patterns.类模式中不应重复相同的关键字。
The following is the logical flow for matching a class pattern against a subject value:以下是将类模式与主题值进行匹配的逻辑流程:
If如果name_or_attr
is not an instance of the builtintype
, raiseTypeError
.name_or_attr
不是内置type
的实例,将引发TypeError
。If the subject value is not an instance of如果name_or_attr
(tested viaisinstance()
), the class pattern fails.subject
值不是name_or_attr
的实例(通过isinstance()
测试),则类模式将失败。If no pattern arguments are present, the pattern succeeds.如果不存在模式参数,则模式成功。Otherwise, the subsequent steps depend on whether keyword or positional argument patterns are present.否则,后续步骤取决于是否存在关键字或位置参数模式。For a number of built-in types (specified below), a single positional subpattern is accepted which will match the entire subject; for these types keyword patterns also work as for other types.对于许多内置类型(如下所述),可以接受与整个主题匹配的单个位置子模式;对于这些类型,关键字模式也适用于其他类型。If only keyword patterns are present, they are processed as follows, one by one:如果只存在关键字模式,则按如下方式逐一处理:I.
The keyword is looked up as an attribute on the subject.关键字作为主题的属性进行查找。If this raises an exception other than如果这引发了AttributeError
, the exception bubbles up.AttributeError
以外的异常,则会出现异常。If this raises如果这引发AttributeError
, the class pattern has failed.AttributeError
,则类模式已失败。Else, the subpattern associated with the keyword pattern is matched against the subject’s attribute value.否则,与关键字模式关联的子模式将与主题的属性值匹配。If this fails, the class pattern fails; if this succeeds, the match proceeds to the next keyword.如果失败,则类模式失败;如果成功,匹配将继续到下一个关键字。
II.
If all keyword patterns succeed, the class pattern succeeds.如果所有关键字模式都成功,则类模式成功。If any positional patterns are present, they are converted to keyword patterns using the如果存在任何位置模式,则在匹配之前,将使用类名或属性上的__match_args__
attribute on the classname_or_attr
before matching:__match_args__
属性将其转换为关键字模式:I.
The equivalent of调用getattr(cls, "__match_args__", ())
is called.getattr(cls, "__match_args__", ())
的等效项。If this raises an exception, the exception bubbles up.如果这引发异常,则会出现异常。If the returned value is not a tuple, the conversion fails and如果返回的值不是元组,则转换失败并引发TypeError
is raised.TypeError
。If there are more positional patterns than如果位置模式多于len(cls.__match_args__)
,TypeError
is raised.len(cls.__match_args__)
,则会引发TypeError
。Otherwise, positional pattern否则,位置模式i
is converted to a keyword pattern using__match_args__[i]
as the keyword.i
将使用__match_args__[i]
作为关键字转换为关键字模式。__match_args__[i]
must be a string; if notTypeError
is raised.__match_args__[i]
必须是字符串;如果不是,则引发TypeError
。If there are duplicate keywords,如果存在重复的关键字,则会引发TypeError
is raised.TypeError
。
- II.
Once all positional patterns have been converted to keyword patterns,一旦所有位置模式都转换为关键字模式, the match proceeds as if there were only keyword patterns.匹配过程就像只有关键字模式一样进行。
For the following built-in types the handling of positional subpatterns is different:对于以下内置类型,位置子模式的处理是不同的:These classes accept a single positional argument, and the pattern there is matched against the whole object rather than an attribute.这些类接受单个位置参数,其中的模式与整个对象而不是属性匹配。For example例如,int(0|1)
matches the value0
, but not the values0.0
orFalse
.int(0|1)
与值0
匹配,但与值0.0
或False
不匹配。
In simple terms 简单来说,CLS(P1, attr=P2)
matches only if the following happens:CLS(P1, attr=P2)
仅在以下情况下匹配:
isinstance(<subject>, CLS)
convert使用P1
to a keyword pattern usingCLS.__match_args__
CLS.__match_args__
将P1
转换为关键字模式For each keyword argument对于每个关键字参数attr=P2
:attr=P2
:hasattr(<subject>, "attr")
P2
matches比赛<subject>.attr
…
and so on for the corresponding keyword argument/pattern pair.对于相应的关键字参数/模式对,依此类推。
8.7. Function definitions函数定义¶
A function definition defines a user-defined function object (see section The standard type hierarchy):函数定义定义用户定义的函数对象(请参见“标准类型层次结构”一节):
funcdef ::= [decorators
] "def"funcname
"(" [parameter_list
] ")"
["->"expression
] ":"suite
decorators ::=decorator
+
decorator ::= "@"assignment_expression
NEWLINE
parameter_list ::=defparameter
(","defparameter
)* "," "/" ["," [parameter_list_no_posonly
]]
|parameter_list_no_posonly
parameter_list_no_posonly ::=defparameter
(","defparameter
)* ["," [parameter_list_starargs
]]
|parameter_list_starargs
parameter_list_starargs ::= "*" [parameter
] (","defparameter
)* ["," ["**"parameter
[","]]]
| "**"parameter
[","]
parameter ::=identifier
[":"expression
]
defparameter ::=parameter
["="expression
]
funcname ::=identifier
A function definition is an executable statement. 函数定义是一条可执行语句。Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). 它的执行将当前本地名称空间中的函数名绑定到函数对象(围绕函数的可执行代码的包装器)。This function object contains a reference to the current global namespace as the global namespace to be used when the function is called.此函数对象包含对当前全局命名空间的引用,作为调用函数时要使用的全局命名空间。
The function definition does not execute the function body; this gets executed only when the function is called. 函数定义不执行函数体;这仅在调用函数时执行。4
A function definition may be wrapped by one or more decorator expressions. 函数定义可以由一个或多个装饰符表达式包装。Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. 定义函数时,将在包含函数定义的范围内计算装饰器表达式。The result must be a callable, which is invoked with the function object as the only argument. 结果必须是一个可调用的,它是以函数对象作为唯一参数调用的。The returned value is bound to the function name instead of the function object. 返回的值绑定到函数名,而不是函数对象。Multiple decorators are applied in nested fashion. 多个装饰器以嵌套方式应用。For example, the following code例如,以下代码
@f1(arg)
@f2
def func(): pass
is roughly equivalent to大致相当于
def func(): pass
func = f1(arg)(f2(func))
except that the original function is not temporarily bound to the name 除了原始函数没有临时绑定到名称func
.func
之外。
Changed in version 3.9:版本3.9中更改: Functions may be decorated with any valid 函数可以用任何有效的assignment_expression
. assignment_expression
修饰。Previously, the grammar was much more restrictive; see PEP 614 for details.以前,语法的限制性要大得多;详见PEP 614。
When one or more parameters have the form parameter 当一个或多个参数的形式为=
expression, the function is said to have “default parameter values.” parameter=expression
时,该函数被称为具有“默认参数值”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.*
”之前的所有后续参数也必须有一个默认值-这是语法中没有表示的语法限制。
Default parameter values are evaluated from left to right when the function definition is executed.执行函数定义时,将从左到右计算默认参数值。 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 value 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 parameter 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.:None
作为默认值,并在函数体中显式测试它,例如:
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 Calls. 函数调用语义将在调用一节中进行更详细的描述。A function call always assigns values to all parameters mentioned in the parameter list, either from positional 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. *identifier
”,则将其初始化为接收任何多余位置参数的元组,默认为空元组。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. **identifier
”,则会将其初始化为新的有序映射,并接收任何多余的关键字参数,默认为相同类型的新空映射。Parameters after ““*
” or “*identifier
” are keyword-only parameters and may only be passed by keyword arguments. *
”或“*identifier
”后的参数是仅限关键字的参数,只能通过关键字参数传递。Parameters before ““/
” are positional-only parameters and may only be passed by positional arguments./
”之前的参数是仅位置参数,只能由位置参数传递。
Changed in version 3.8:版本3.8中更改: The /
function parameter syntax may be used to indicate positional-only parameters. /
函数参数语法可用于指示仅位置参数。See PEP 570 for details.详见PEP 570。
Parameters may have an annotation of the form “参数名称后面可能有一个格式为“: expression
” following the parameter name. : expression
”的注释。Any parameter may have an annotation, even those of the form 任何参数都可以有注释,甚至是“*identifier
or **identifier
. *identifier
”或“**identifier
”形式的注释。Functions may have “return” annotation of the form “函数可以在参数列表后有“-> expression
” after the parameter list. -> expression
”形式的“return”注释。These annotations can be any valid Python expression. 这些注释可以是任何有效的Python表达式。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__
attribute of the function object. __annotations__
属性中的参数名称进行键控。If the 如果使用从annotations
import from __future__
is used, annotations are preserved as strings at runtime which enables postponed evaluation. __future__
导入的annotations
,则注释将在运行时保留为字符串,从而启用延迟的计算。Otherwise, they are evaluated when the function definition is executed. 否则,将在执行函数定义时对其进行计算。In this case annotations may be evaluated in a different order than they appear in the source code.在这种情况下,注释的求值顺序可能与它们在源代码中出现的顺序不同。
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. 这使用lambda表达式,如Lambdas一节所述。Note that the lambda expression is merely a shorthand for a simplified function definition; a function defined in a “请注意,lambda表达式只是简化函数定义的简写;“def
” statement can be passed around or assigned to another name just like a function defined by a lambda expression. def
”语句中定义的函数可以传递或分配给其他名称,就像lambda表达式定义的函数一样。The ““def
” form is actually more powerful since it allows the execution of multiple statements and annotations.def
”表单实际上更强大,因为它允许执行多个语句和注释。
Programmer’s note: Functions are first-class objects. 函数是一级对象。A “在函数定义中执行的“def
” statement executed inside a function definition defines a local function that can be returned or passed around. def
”语句定义了可以返回或传递的本地函数。Free variables used in the nested function can access the local variables of the function containing the def. 嵌套函数中使用的自由变量可以访问包含def的函数的局部变量。See section Naming and binding for details.有关详细信息,请参阅命名和绑定部分。
See also参阅
- PEP 3107 -
Function Annotations函数注解 The original specification for function annotations.函数注释的原始规范。- PEP 484 -
Type Hints键入提示 Definition of a standard meaning for annotations: type hints.注释的标准含义定义:键入提示。- PEP 526 -
Syntax for Variable Annotations变量注释的语法 Ability to type hint variable declarations, including class variables and instance variables能够键入提示变量声明,包括类变量和实例变量- PEP 563 -
Postponed Evaluation of Annotations延期评估注释 Support for forward references within annotations by preserving annotations in a string form at runtime instead of eager evaluation.通过在运行时以字符串形式保留注释,而不是急于求值,支持在注释内转发引用。
8.8. Class definitions类定义¶
A class definition defines a class object (see section The standard type hierarchy):类定义定义了类对象(请参见“标准类型层次结构”一节):
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,object
继承;因此
class Foo:
pass
is equivalent to相当于
class Foo(object):
pass
The class’s suite is then executed in a new execution frame (see Naming and binding), 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. 当类的套件完成执行时,将丢弃其执行框架,但会保存其本地命名空间。5 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__
. __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
is roughly equivalent to大致相当于
class Foo: pass
Foo = f1(arg)(f2(Foo))
The evaluation rules for the decorator expressions are the same as for function decorators. decorator表达式的计算规则与函数decorator的计算规则相同。The result is then bound to the class name.然后将结果绑定到类名。
Changed in version 3.9:版本3.9中更改: Classes may be decorated with any valid 类可以用任何有效的assignment_expression
. assignment_expression
修饰。Previously, the grammar was much more restrictive; see PEP 614 for details.以前,语法的限制性要大得多;详见PEP 614。
Programmer’s note: 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
. 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. self.name
”访问,并且实例属性在以这种方式访问时隐藏具有相同名称的类属性。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.可以用于创建具有不同实现细节的实例变量。
See also参阅
- PEP 3115 - Metaclasses in 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 - Class Decorators
The proposal that added class decorators.添加类装饰器的建议。Function and method decorators were introduced in PEP 318.PEP 318中介绍了装饰器的功能和方法。
8.9. Coroutines协同程序¶
New in version 3.5.版本3.5中新增。
8.9.1. Coroutine function definition协同例程函数定义¶
async_funcdef ::= [decorators
] "async" "def"funcname
"(" [parameter_list
] ")"
["->"expression
] ":"suite
Execution of Python coroutines can be suspended and resumed at many points (see coroutine). Python协同路由的执行可以在多个点暂停和恢复(请参见协同例程)。await
expressions, async for
and async with
can only be used in the body of a coroutine function.await
表达式、async for
和async with
只能在协同例程函数的主体中使用。
Functions defined with 使用async def
syntax are always coroutine functions, even if they do not contain await
or async
keywords.async def
语法定义的函数始终是协程函数,即使它们不包含await
或async
关键字。
It is a 在协同例程函数体中使用SyntaxError
to use a yield from
expression inside the body of a coroutine function.yield from
表达式是一种SyntaxError
。
An example of a coroutine function:协同例程函数的一个示例:
async def func(param1, param2):
do_stuff()
await some_coroutine()
Changed in version 3.7:版本3.7中更改: await
and async
are now keywords; previously they were only treated as such inside the body of a coroutine function.await
和async
现在是关键字;以前,它们仅在协同例程函数的主体内被视为这样处理。
8.9.2. The async for
statementasync for
语句¶
async for
statementasync_for_stmt ::= "async" for_stmt
An asynchronous iterable provides an 异步iterable提供了一个__aiter__
method that directly returns an asynchronous iterator, which can call asynchronous code in its __anext__
method.__aiter__
方法,该方法直接返回异步迭代器,该迭代器可以在其__anext__
方法中调用异步代码。
The async for
statement allows convenient iteration over asynchronous iterables.async for
语句允许在异步iterables上进行方便的迭代。
The following code:以下代码:
async for TARGET in ITER:
SUITE
else:
SUITE2
Is semantically equivalent to:在语义上等同于:
iter = (ITER)
iter = type(iter).__aiter__(iter)
running = True
while running:
try:
TARGET = await type(iter).__anext__(iter)
except StopAsyncIteration:
running = False
else:
SUITE
else:
SUITE2
See also 有关详细信息,请参阅__aiter__()
and __anext__()
for details.__aiter__()
和__anext__()
。
It is a 在协同例程函数体外部使用SyntaxError
to use an async for
statement outside the body of a coroutine function.async for
语句是一种SyntaxError
。
8.9.3. The async with
statementasync with
语句¶
async with
statementasync_with_stmt ::= "async" with_stmt
An asynchronous context manager is a context manager that is able to suspend execution in its enter and exit methods.异步上下文管理器是一种上下文管理器,它能够在其enter和exit方法中暂停执行。
The following code:以下代码:
async with EXPRESSION as TARGET:
SUITE
is semantically equivalent to:在语义上等同于:
manager = (EXPRESSION)
aenter = type(manager).__aenter__
aexit = type(manager).__aexit__
value = await aenter(manager)
hit_except = False
try:
TARGET = value
SUITE
except:
hit_except = True
if not await aexit(manager, *sys.exc_info()):
raise
finally:
if not hit_except:
await aexit(manager, None, None, None)
See also 有关详细信息,请参阅__aenter__()
and __aexit__()
for details.__aenter__()
和__aexit__()
。
It is a 在协同例程函数体外部使用SyntaxError
to use an async with
statement outside the body of a coroutine function.async with
语句是一种SyntaxError
。
See also
- PEP 492 -
Coroutines with async and await syntax使用async和await语法的协同路由 The proposal that made coroutines a proper standalone concept in Python, and added supporting syntax.该提案使协同路由在Python中成为一个适当的独立概念,并添加了支持语法。
Footnotes
- 1
The exception is propagated to the invocation stack unless there is a除非有一个finally
clause which happens to raise another exception.finally
子句碰巧引发另一个异常,否则该异常会传播到调用堆栈。That new exception causes the old one to be lost.新的异常会导致旧的异常丢失。- 2
In pattern matching, a sequence is defined as one of the following:在模式匹配中,序列定义为以下之一:a class that inherits from从collections.abc.Sequence
collections.abc.Sequence
继承的类a Python class that has been registered as已注册为collections.abc.Sequence
collections.abc.Sequence
的Python类a builtin class that has its (CPython)设置了(CPython)Py_TPFLAGS_SEQUENCE
bit setPy_TPFLAGS_SEQUENCE
位的内置类a class that inherits from any of the above从上述任何一个继承的类
The following standard library classes are sequences:以下标准库类是序列:Note
Subject values of typestr
,bytes
, andbytearray
do not match sequence patterns.str
、bytes
和bytearray
类型的主题值与序列模式不匹配。- 3
In pattern matching, a mapping is defined as one of the following:在模式匹配中,映射定义为以下之一:a class that inherits from从collections.abc.Mapping
collections.abc.Mapping
继承的类a Python class that has been registered as已注册为collections.abc.Mapping
collections.abc.Mapping
的Python类a builtin class that has its (CPython)设置了(CPython)Py_TPFLAGS_MAPPING
bit setPy_TPFLAGS_MAPPING
位的内置类a class that inherits from any of the above从上述任何一个继承的类
The standard library classes标准库类dict
andtypes.MappingProxyType
are mappings.dict
和types.MappingProxyType
类型是映射。- 4
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.__doc__
属性,从而转换为函数的docstring。- 5
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.__doc__
项,从而转换为类的docstring。