6. Expressions表达式

This chapter explains the meaning of the elements of expressions in Python.本章解释Python中表达式元素的含义。

Syntax Notes:语法注释: In this and the following chapters, extended BNF notation will be used to describe syntax, not lexical analysis. 在本章和后续章节中,扩展BNF符号将用于描述语法,而不是词法分析。When (one alternative of) a syntax rule has the form当语法规则的(一种替代)具有以下形式时


name ::= othername

and no semantics are given, the semantics of this form of name are the same as for othername.并且没有给出语义,这种形式的name的语义与othername的语义相同。

6.1. Arithmetic conversions算术转换

When a description of an arithmetic operator below uses the phrase “the numeric arguments are converted to a common type”, this means that the operator implementation for built-in types works as follows:当下面的算术运算符描述使用短语“数值参数转换为公共类型”时,这意味着内置类型的运算符实现的工作方式如下:

  • If either argument is a complex number, the other is converted to complex;如果其中一个参数是复数,则另一个参数将转换为复数;

  • otherwise, if either argument is a floating point number, the other is converted to floating point;否则,如果其中一个参数是浮点数,则另一个参数将转换为浮点数;

  • otherwise, both must be integers and no conversion is necessary.否则,两者都必须是整数,无需转换。

Some additional rules apply for certain operators (e.g., a string as a left argument to the ‘%’ operator). 某些附加规则适用于某些运算符(例如,字符串作为“%”运算符的左参数)。Extensions must define their own conversion behavior.扩展必须定义自己的转换行为。

6.2. Atoms原子

Atoms are the most basic elements of expressions. 原子是表达式最基本的元素。The simplest atoms are identifiers or literals. 最简单的原子是标识符或文字。Forms enclosed in parentheses, brackets or braces are also categorized syntactically as atoms. 括号、括号或大括号中的形式在语法上也被归类为原子。The syntax for atoms is:atoms的语法为:


atom ::= identifier | literal | enclosure
enclosure ::= parenth_form | list_display | dict_display | set_display
| generator_expression | yield_atom

6.2.1. Identifiers (Names)标识符(名称)

An identifier occurring as an atom is a name. 作为原子出现的标识符是名称。See section Identifiers and keywords for lexical definition and section Naming and binding for documentation of naming and binding.有关命名和绑定的文档,请参阅标识符和关键字部分以及命名和绑定部分以了解词汇定义。

When the name is bound to an object, evaluation of the atom yields that object. 当名称绑定到对象时,对原子的求值将生成该对象。When a name is not bound, an attempt to evaluate it raises a NameError exception.如果名称未绑定,尝试对其求值将引发NameError异常。

Private name mangling:私有名称损坏: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. 如果在类定义中以文本形式出现的标识符以两个或多个下划线字符开头,而不是以两个或多个下划线结尾,则该标识符被视为该类的私有名称Private names are transformed to a longer form before code is generated for them. 在为私有名称生成代码之前,会将其转换为更长的形式。The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. 转换将在名称前面插入类名,删除前导下划线并插入一个下划线。For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. 例如,名为Ham的类中出现的标识符__spam将转换为_Ham__spamThis transformation is independent of the syntactical context in which the identifier is used. 这种转换与使用标识符的语法上下文无关。If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. 如果转换后的名称非常长(超过255个字符),则可能会发生实现定义的截断。If the class name consists only of underscores, no transformation is done.如果类名只包含下划线,则不会进行转换。

6.2.2. Literals直接常量

Python supports string and bytes literals and various numeric literals:Python支持字符串和字节文本以及各种数字文本:


literal ::= stringliteral | bytesliteral
| integer | floatnumber | imagnumber

Evaluation of a literal yields an object of the given type (string, bytes, integer, floating point number, complex number) with the given value. 对文本的求值将生成具有给定值的给定类型(字符串、字节、整数、浮点数、复数)的对象。The value may be approximated in the case of floating point and imaginary (complex) literals. 在浮点和虚(复)字面值的情况下,该值可以近似。See section Literals for details.有关详细信息,请参阅文字部分。

All literals correspond to immutable data types, and hence the object’s identity is less important than its value. 所有文字都对应于不可变的数据类型,因此对象的标识不如其值重要。Multiple evaluations of literals with the same value (either the same occurrence in the program text or a different occurrence) may obtain the same object or a different object with the same value.对具有相同值(程序文本中的相同匹配项或不同匹配项)的文本进行多次求值可能会获得相同的对象或具有相同值的不同对象。

6.2.3. Parenthesized forms括号表达式

A parenthesized form is an optional expression list enclosed in parentheses:带圆括号的形式是用圆括号括起来的可选表达式列表:


parenth_form ::= "(" [starred_expression] ")"

A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.带圆括号的表达式列表产生表达式列表产生的结果:如果列表至少包含一个逗号,则产生一个元组;否则,它将生成组成表达式列表的单个表达式。

An empty pair of parentheses yields an empty tuple object. 一对空括号生成一个空的tuple对象。Since tuples are immutable, the same rules as for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object).由于元组是不可变的,因此适用与文本相同的规则(即,两次出现空元组可能会产生或可能不会产生相同的对象)。

Note that tuples are not formed by the parentheses, but rather by use of the comma operator. 请注意,元组不是由括号组成的,而是由逗号运算符组成的。The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.空元组是一个例外,它需要括号——在表达式中允许未附加括号的“nothing”将导致歧义,并允许常见的拼写错误不受影响地传递。

6.2.4. Displays for lists, sets and dictionaries显示列表、集合和词典

For constructing a list, a set or a dictionary Python provides special syntax called “displays”, each of them in two flavors:为了构造列表,集合或字典Python提供了称为“displays”的特殊语法,每种语法都有两种风格:

  • either the container contents are listed explicitly, or明确列出容器内容,或

  • they are computed via a set of looping and filtering instructions, called a comprehension.它们是通过一组循环和筛选指令(称为推导)计算的。

Common syntax elements for comprehensions are:推导的常见语法元素有:


comprehension ::= assignment_expression comp_for
comp_for ::= ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter ::= comp_for | comp_if
comp_if ::= "if" or_test [comp_iter]

The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. 推导包括一个表达式,后跟至少一个for子句和零个或多个forif子句。In this case, the elements of the new container are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached.在这种情况下,新容器的元素是通过将每个forif子句视为块、从左到右嵌套并在每次到达最里面的块时计算表达式以生成元素而生成的元素。

However, aside from the iterable expression in the leftmost for clause, the comprehension is executed in a separate implicitly nested scope. 然而,除了最左边的for子句中的iterable表达式之外,推导是在一个单独的隐式嵌套范围中执行的。This ensures that names assigned to in the target list don’t “leak” into the enclosing scope.这可以确保在目标列表中指定给的名称不会“泄漏”到封闭范围中。

The iterable expression in the leftmost for clause is evaluated directly in the enclosing scope and then passed as an argument to the implicitly nested scope. 最左侧for子句中的iterable表达式直接在封闭范围中求值,然后作为参数传递给隐式嵌套范围。Subsequent for clauses and any filter condition in the leftmost for clause cannot be evaluated in the enclosing scope as they may depend on the values obtained from the leftmost iterable. 不能在封闭范围内计算最左侧for子句中的后续for子句和任何筛选条件,因为它们可能取决于从最左侧iterable获得的值。For example: [x*y for x in range(10) for y in range(x, x+10)].例如:[x*y for x in range(10) for y in range(x, x+10)]

To ensure the comprehension always results in a container of the appropriate type, yield and yield from expressions are prohibited in the implicitly nested scope.为了确保推导总是产生一个适当类型的容器,在隐式嵌套范围中禁止使用yieldyield from表达式。

Since Python 3.6, in an async def function, an async for clause may be used to iterate over a asynchronous iterator. 自Python 3.6以来,在async def函数中,可以使用async for子句迭代异步迭代器。A comprehension in an async def function may consist of either a for or async for clause following the leading expression, may contain additional for or async for clauses, and may also use await expressions. async def函数中的推导可能包含前导表达式后面的forasync for子句,可能包含其他forasync for子句,还可能使用await表达式。If a comprehension contains either async for clauses or await expressions it is called an asynchronous comprehension. 如果推导包含async for子句或await表达式,则称为异步推导An asynchronous comprehension may suspend the execution of the coroutine function in which it appears. 异步推导可能会暂停其出现的协同例程函数的执行。See also PEP 530.另见PEP 530

New in version 3.6.版本3.6中新增。Asynchronous comprehensions were introduced.引入了异步推导。

Changed in version 3.8:版本3.8中更改: yield and yield from prohibited in the implicitly nested scope.在隐式嵌套的作用域中禁止使用yieldyield from

6.2.5. List displays显示

A list display is a possibly empty series of expressions enclosed in square brackets:列表显示可能是方括号中的一系列空表达式:


list_display ::= "[" [starred_list | comprehension] "]"

A list display yields a new list object, the contents being specified by either a list of expressions or a comprehension. 列表显示生成一个新的列表对象,内容由表达式列表或理解指定。When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and placed into the list object in that order. 如果提供了以逗号分隔的表达式列表,则将从左到右计算其元素,并按该顺序将其放置到列表对象中。When a comprehension is supplied, the list is constructed from the elements resulting from the comprehension.当提供理解时,列表是由理解产生的元素构成的。

6.2.6. Set displays显示

A set display is denoted by curly braces and distinguishable from dictionary displays by the lack of colons separating keys and values:集合显示用大括号表示,由于缺少分隔键和值的冒号,因此与字典显示不同:


set_display ::= "{" (starred_list | comprehension) "}"

A set display yields a new mutable set object, the contents being specified by either a sequence of expressions or a comprehension. 集合显示生成一个新的可变集合对象,其内容由表达式序列或理解指定。When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and added to the set object. 如果提供了以逗号分隔的表达式列表,则将从左到右计算其元素,并将其添加到集合对象中。When a comprehension is supplied, the set is constructed from the elements resulting from the comprehension.当提供理解时,集合是由理解产生的元素构成的。

An empty set cannot be constructed with {}; this literal constructs an empty dictionary.空集不能用{}构造;此文本构造一个空字典。

6.2.7. Dictionary displays显示

A dictionary display is a possibly empty series of key/datum pairs enclosed in curly braces:字典显示可能是一系列空的键/数据对,用花括号括起来:


dict_display ::= "{" [key_datum_list | dict_comprehension] "}"
key_datum_list ::= key_datum ("," key_datum)* [","]
key_datum ::= expression ":" expression | "**" or_expr
dict_comprehension ::= expression ":" expression comp_for

A dictionary display yields a new dictionary object.字典显示将生成一个新的字典对象。

If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum. 如果给定了以逗号分隔的键/数据对序列,则会从左到右对其求值,以定义字典的条目:每个键对象都用作字典中的键,以存储相应的数据。This means that you can specify the same key multiple times in the key/datum list, and the final dictionary’s value for that key will be the last one given.这意味着您可以在键/基准列表中多次指定同一键,该键的最终字典值将是最后给定的值。

A double asterisk ** denotes dictionary unpacking. 双星号**表示字典解包Its operand must be a mapping. 其操作数必须是映射Each mapping item is added to the new dictionary. 每个映射项都将添加到新词典中。Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.以后的值替换以前的键/数据对和早期字典解包已经设置的值。

New in version 3.5.版本3.5中新增。Unpacking into dictionary displays, originally proposed by PEP 448.解包到字典显示,最初由PEP 448提出。

A dict comprehension, in contrast to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses. 与列表和集合理解不同,dict理解需要两个表达式,用冒号分隔,后跟通常的“for”和“if”子句。When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.运行理解时,生成的键和值元素将按生成顺序插入新词典中。

Restrictions on the types of the key values are listed earlier in section The standard type hierarchy. 键值类型的限制在前面的标准类型层次结构部分中列出。(To summarize, the key type should be hashable, which excludes all mutable objects.) (总而言之,键类型应该是可哈希的,它排除了所有可变对象。)Clashes between duplicate keys are not detected; the last datum (textually rightmost in the display) stored for a given key value prevails.未检测到重复关键点之间的碰撞;以为给定键值存储的最后一个基准(显示屏中文本最右侧)为准。

Changed in version 3.8:版本3.8中更改: Prior to Python 3.8, in dict comprehensions, the evaluation order of key and value was not well-defined. 在Python 3.8之前,在dict理解中,键和值的求值顺序没有很好的定义。In CPython, the value was evaluated before the key. 在CPython中,值是在键之前计算的。Starting with 3.8, the key is evaluated before the value, as proposed by PEP 572.从3.8开始,按照PEP 572的建议,在值之前评估键。

6.2.8. Generator expressions生成器表达式

A generator expression is a compact generator notation in parentheses:生成器表达式是括号中的紧凑生成器表示法:


generator_expression ::= "(" expression comp_for ")"

A generator expression yields a new generator object. Its syntax is the same as for comprehensions, except that it is enclosed in parentheses instead of brackets or curly braces.生成器表达式生成新的生成器对象。它的语法与理解的语法相同,只是它被括在括号中,而不是括号或大括号中。

Variables used in the generator expression are evaluated lazily when the __next__() method is called for the generator object (in the same fashion as normal generators). 当为生成器对象调用__next__()方法时,生成器表达式中使用的变量将延迟求值(与普通生成器的方式相同)。However, the iterable expression in the leftmost for clause is immediately evaluated, so that an error produced by it will be emitted at the point where the generator expression is defined, rather than at the point where the first value is retrieved. 但是,将立即计算最左侧for子句中的iterable表达式,以便在定义生成器表达式的点而不是在检索第一个值的点发出由它产生的错误。Subsequent for clauses and any filter condition in the leftmost for clause cannot be evaluated in the enclosing scope as they may depend on the values obtained from the leftmost iterable. 不能在封闭范围内计算最左侧for子句中的后续for子句和任何筛选条件,因为它们可能取决于从最左侧iterable获得的值。For example: (x*y for x in range(10) for y in range(x, x+10)).例如:(x*y for x in range(10) for y in range(x, x+10))

The parentheses can be omitted on calls with only one argument. 只有一个参数的调用可以省略括号。See section Calls for details.有关详细信息,请参阅调用部分。

To avoid interfering with the expected operation of the generator expression itself, yield and yield from expressions are prohibited in the implicitly defined generator.为了避免干扰生成器表达式本身的预期操作,隐式定义的生成器中禁止表达式的yieldyield from

If a generator expression contains either async for clauses or await expressions it is called an asynchronous generator expression. 如果生成器表达式包含async for子句或await表达式,则称为异步生成器表达式An asynchronous generator expression returns a new asynchronous generator object, which is an asynchronous iterator (see Asynchronous Iterators).异步生成器表达式返回一个新的异步生成器对象,该对象是异步迭代器(请参见异步迭代器)。

New in version 3.6.版本3.6中新增。Asynchronous generator expressions were introduced.介绍了异步生成器表达式。

Changed in version 3.7:版本3.7中更改: Prior to Python 3.7, asynchronous generator expressions could only appear in async def coroutines. 在Python 3.7之前,异步生成器表达式只能出现在async def协同例程中。Starting with 3.7, any function can use asynchronous generator expressions.从3.7开始,任何函数都可以使用异步生成器表达式。

Changed in version 3.8:版本3.8中更改: yield and yield from prohibited in the implicitly nested scope.在隐式嵌套的作用域中禁止使用yieldyield from

6.2.9. yield expressions表达式


yield_atom ::= "(" yield_expression ")"
yield_expression ::= "yield" [expression_list | "from" expression]

The yield expression is used when defining a generator function or an asynchronous generator function and thus can only be used in the body of a function definition. yield表达式用于定义生成器函数或异步生成器函数,因此只能在函数定义的主体中使用。Using a yield expression in a function’s body causes that function to be a generator function, and using it in an async def function’s body causes that coroutine function to be an asynchronous generator function. 在函数体中使用屈服表达式会使该函数成为生成器函数,而在async def函数体中使用屈服表达式会使该协程函数成为异步生成器函数。For example:例如:

def gen():  # defines a generator function
yield 123
async def agen(): # defines an asynchronous generator function
yield 123

Due to their side effects on the containing scope, yield expressions are not permitted as part of the implicitly defined scopes used to implement comprehensions and generator expressions.由于其对包含范围的副作用,不允许将yield表达式作为用于实现理解和生成器表达式的隐式定义范围的一部分。

Changed in version 3.8:版本3.8中更改: Yield expressions prohibited in the implicitly nested scopes used to implement comprehensions and generator expressions.在用于实现理解和生成器表达式的隐式嵌套作用域中禁止生成表达式。

Generator functions are described below, while asynchronous generator functions are described separately in section Asynchronous generator functions.生成器功能如下所述,异步生成器函数在异步生成器函数部分中单独描述。

When a generator function is called, it returns an iterator known as a generator. 调用生成器函数时,它返回一个称为生成器的迭代器。That generator then controls the execution of the generator function. 然后,该生成器控制生成器功能的执行。The execution starts when one of the generator’s methods is called. 在调用生成器的一个方法时开始执行。At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to the generator’s caller. 此时,执行继续到第一个yield表达式,在那里它再次被挂起,并将expression_list的值返回给生成器的调用者。By suspended, we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. 挂起表示保留所有局部状态,包括局部变量的当前绑定、指令指针、内部求值堆栈和任何异常处理的状态。When the execution is resumed by calling one of the generator’s methods, the function can proceed exactly as if the yield expression were just another external call. 当通过调用生成器的一个方法恢复执行时,该函数可以像yield表达式只是另一个外部调用一样继续执行。The value of the yield expression after resuming depends on the method which resumed the execution. 恢复后的yield表达式的值取决于恢复执行的方法。If __next__() is used (typically via either a for or the next() builtin) then the result is None. 如果使用了__next__()(通常通过fornext()内置),则结果为NoneOtherwise, if send() is used, then the result will be the value passed in to that method.否则,如果使用send(),则结果将是传入该方法的值。

All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than one entry point and their execution can be suspended. 所有这些使得生成器的功能与协同程序非常相似;它们多次屈服,有多个入口点,可以暂停执行。The only difference is that a generator function cannot control where the execution should continue after it yields; the control is always transferred to the generator’s caller.唯一的区别是,生成器函数无法控制在生成后执行应该在哪里继续;控制权始终转移到生成器的调用者。

Yield expressions are allowed anywhere in a try construct. try构造中的任何位置都允许使用yield表达式。If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator’s close() method will be called, allowing any pending finally clauses to execute.如果生成器在最终确定之前没有恢复(通过达到零引用计数或被垃圾收集),将调用生成器迭代器的close()方法,从而允许执行任何挂起的finally子句。

When yield from <expr> is used, the supplied expression must be an iterable. 当使用yield from<expr>时,提供的表达式必须是iterable。The values produced by iterating that iterable are passed directly to the caller of the current generator’s methods. 迭代iterable生成的值直接传递给当前生成器方法的调用方。Any values passed in with send() and any exceptions passed in with throw() are passed to the underlying iterator if it has the appropriate methods. 使用send()传入的任何值和使用throw()传入的任何异常都会传递给基础迭代器(如果它具有适当的方法)。If this is not the case, then send() will raise AttributeError or TypeError, while throw() will just raise the passed in exception immediately.如果不是这样,则send()将引发AttributeErrorTypeError,而throw()将立即引发传入的异常。

When the underlying iterator is complete, the value attribute of the raised StopIteration instance becomes the value of the yield expression. 当基础迭代器完成时,引发的StopIteration实例的value属性将成为yield表达式的值。It can be either set explicitly when raising StopIteration, or automatically when the subiterator is a generator (by returning a value from the subgenerator).它可以在引发StopIteration时显式设置,也可以在子迭代器是生成器时自动设置(通过从子生成器返回值)。

Changed in version 3.3:版本3.3中更改: Added yield from <expr> to delegate control flow to a subiterator.添加了yield from <expr>,以将控制流委托给子迭代器。

The parentheses may be omitted when the yield expression is the sole expression on the right hand side of an assignment statement.yield表达式是赋值语句右侧的唯一表达式时,可以省略括号。

See also

PEP 255 - Simple Generators简单生成器

The proposal for adding generators and the yield statement to Python.向Python中添加生成器和yield语句的建议。

PEP 342 - Coroutines via Enhanced Generators通过增强型生成器实现协同路由

The proposal to enhance the API and syntax of generators, making them usable as simple coroutines.建议增强生成器的API和语法,使其可用作简单的协同例程。

PEP 380 - Syntax for Delegating to a Subgenerator委托给子生成器的语法

The proposal to introduce the yield_from syntax, making delegation to subgenerators easy.引入yield_from语法的目的,是使委托给子生成器变得容易。

PEP 525 - Asynchronous Generators异步生成器

The proposal that expanded on PEP 492 by adding generator capabilities to coroutine functions.通过将生成器功能添加到协同例程函数,扩展了PEP 492的建议。

6.2.9.1. Generator-iterator methods生成器迭代器方法

This subsection describes the methods of a generator iterator. 本小节描述生成器迭代器的方法。They can be used to control the execution of a generator function.它们可用于控制生成器功能的执行。

Note that calling any of the generator methods below when the generator is already executing raises a ValueError exception.请注意,当生成器已经在执行时调用下面的任何生成器方法都会引发ValueError异常。

generator.__next__()

Starts the execution of a generator function or resumes it at the last executed yield expression. 开始执行生成器函数,或在最后执行的yield表达式处继续执行。When a generator function is resumed with a __next__() method, the current yield expression always evaluates to None. 使用__next__()方法恢复生成器函数时,当前产量表达式的计算结果始终为NoneThe execution then continues to the next yield expression, where the generator is suspended again, and the value of the expression_list is returned to __next__()’s caller. 然后执行继续到下一个yield表达式,其中生成器再次挂起,expression_list的值返回给__next__()的调用者。If the generator exits without yielding another value, a StopIteration exception is raised.如果生成器退出而不生成其他值,则会引发StopIteration异常。

This method is normally called implicitly, e.g. by a for loop, or by the built-in next() function.此方法通常隐式调用,例如由for循环或内置的next()函数调用。

generator.send(value)

Resumes the execution and “sends” a value into the generator function. 恢复执行并向生成器函数“发送”值。The value argument becomes the result of the current yield expression. value参数将成为当前yield表达式的结果。The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. send()方法返回生成器生成的下一个值,如果生成器退出而不生成其他值,则会引发StopIterationWhen send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value.当调用send()来启动生成器时,必须以None作为参数来调用它,因为没有可以接收该值的yield表达式。

generator.throw(value)
generator.throw(type[, value[, traceback]])

Raises an exception at the point where the generator was paused, and returns the next value yielded by the generator function. 在生成器暂停的点引发异常,并返回生成器函数生成的下一个值。If the generator exits without yielding another value, a StopIteration exception is raised. 如果生成器退出而不生成其他值,则会引发StopIteration异常。If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller.如果生成器函数未捕获传入的异常,或引发其他异常,则该异常会传播到调用方。

In typical use, this is called with a single exception instance similar to the way the raise keyword is used.在典型使用中,这是通过一个异常实例调用的,类似于raise关键字的使用方式。

For backwards compatability, however, the second signature is supported, following a convention from older versions of Python. 然而,为了向后兼容,第二个签名是受支持的,它遵循了Python旧版本的约定。The type argument should be an exception class, and value should be an exception instance. type参数应为异常类,value应为异常实例。If the value is not provided, the type constructor is called to get an instance. 如果未提供该value,则调用type构造函数以获取实例。If traceback is provided, it is set on the exception, otherwise any existing __traceback__ attribute stored in value may be cleared.如果提供了traceback,则将其设置为异常,否则可能会清除存储在value中的任何现有__traceback__属性。

generator.close()

Raises a GeneratorExit at the point where the generator function was paused. 在生成器函数暂停的点引发GeneratorExitIf the generator function then exits gracefully, is already closed, or raises GeneratorExit (by not catching the exception), close returns to its caller. 如果生成器函数随后正常退出、已关闭或引发GeneratorExit(通过不捕获异常),则close将返回其调用者。If the generator yields a value, a RuntimeError is raised. 如果生成器生成一个值,则会引发RuntimeErrorIf the generator raises any other exception, it is propagated to the caller. 如果生成器引发任何其他异常,则会将其传播到调用方。close() does nothing if the generator has already exited due to an exception or normal exit.如果生成器由于异常或正常退出而已退出,则不执行任何操作。

6.2.9.2. Examples示例

Here is a simple example that demonstrates the behavior of generators and generator functions:下面是一个演示生成器和生成器函数行为的简单示例:

>>> def echo(value=None):
... print("Execution starts when 'next()' is called for the first time.")
... try:
... while True:
... try:
... value = (yield value)
... except Exception as e:
... value = e
... finally:
... print("Don't forget to clean up when 'close()' is called.")
...
>>> generator = echo(1)
>>> print(next(generator))
Execution starts when 'next()' is called for the first time.
1
>>> print(next(generator))
None
>>> print(generator.send(2))
2
>>> generator.throw(TypeError, "spam")
TypeError('spam',)
>>> generator.close()
Don't forget to clean up when 'close()' is called.

For examples using yield from, see PEP 380: Syntax for Delegating to a Subgenerator in “What’s New in Python.”有关使用yield from的示例,请参阅“Python中的新增功能”中的PEP 380:委托给子生成器的语法

6.2.9.3. Asynchronous generator functions异步生成器功能

The presence of a yield expression in a function or method defined using async def further defines the function as an asynchronous generator function.如果在使用async def定义的函数或方法中存在屈服表达式,则会进一步将该函数定义为异步生成器函数。

When an asynchronous generator function is called, it returns an asynchronous iterator known as an asynchronous generator object. 调用异步生成器函数时,它返回一个称为异步生成器对象的异步迭代器。That object then controls the execution of the generator function. 然后,该对象控制生成器函数的执行。An asynchronous generator object is typically used in an async for statement in a coroutine function analogously to how a generator object would be used in a for statement.异步生成器对象通常在协同例程函数的async for语句中使用,类似于生成器对象在for语句中的使用方式。

Calling one of the asynchronous generator’s methods returns an awaitable object, and the execution starts when this object is awaited on. 调用异步生成器的一个方法将返回一个可等待的对象,并在等待该对象时开始执行。At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to the awaiting coroutine. 此时,执行继续到第一个yield表达式,在那里它再次被挂起,并将expression_list的值返回到等待的协同例程。As with a generator, suspension means that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. 与生成器一样,挂起意味着保留所有局部状态,包括局部变量的当前绑定、指令指针、内部求值堆栈和任何异常处理的状态。When the execution is resumed by awaiting on the next object returned by the asynchronous generator’s methods, the function can proceed exactly as if the yield expression were just another external call. 当通过等待异步生成器的方法返回的下一个对象来恢复执行时,函数可以完全继续,就像yield表达式只是另一个外部调用一样。The value of the yield expression after resuming depends on the method which resumed the execution. 恢复后的yield表达式的值取决于恢复执行的方法。If __anext__() is used then the result is None. 如果使用了__anext__(),则结果为NoneOtherwise, if asend() is used, then the result will be the value passed in to that method.否则,如果使用asend(),则结果将是传入该方法的值。

If an asynchronous generator happens to exit early by break, the caller task being cancelled, or other exceptions, the generator’s async cleanup code will run and possibly raise exceptions or access context variables in an unexpected context–perhaps after the lifetime of tasks it depends, or during the event loop shutdown when the async-generator garbage collection hook is called. 如果异步生成器使用break提前退出、调用方任务被取消,或出现其他异常,则生成器的异步清理代码将运行,并可能在意外上下文中引发异常或访问上下文变量,可能是在它所依赖的任务生存期之后,或在调用异步生成器垃圾收集挂钩时的事件循环关闭期间。To prevent this, the caller must explicitly close the async generator by calling aclose() method to finalize the generator and ultimately detach it from the event loop.为了防止出现这种情况,调用方必须通过调用aclose()方法显式关闭异步生成器,以完成生成器并最终将其与事件循环分离。

In an asynchronous generator function, yield expressions are allowed anywhere in a try construct. 在异步生成器函数中,try构造中的任何位置都允许使用yield表达式。However, if an asynchronous generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), then a yield expression within a try construct could result in a failure to execute pending finally clauses. 但是,如果异步生成器在最终确定之前没有恢复(通过达到零引用计数或被垃圾收集),那么try构造中的yield表达式可能会导致执行挂起的finally子句失败。In this case, it is the responsibility of the event loop or scheduler running the asynchronous generator to call the asynchronous generator-iterator’s aclose() method and run the resulting coroutine object, thus allowing any pending finally clauses to execute.在这种情况下,运行异步生成器的事件循环或调度程序负责调用异步生成器迭代器的aclose()方法并运行生成的协同例程对象,从而允许执行任何挂起的finally子句。

To take care of finalization upon event loop termination, an event loop should define a finalizer function which takes an asynchronous generator-iterator and presumably calls aclose() and executes the coroutine. 为了在事件循环终止时完成终结,事件循环应该定义一个终结器函数,该函数接受异步生成器迭代器,并可能调用aclose()并执行协同例程。This finalizer may be registered by calling sys.set_asyncgen_hooks(). 可以通过调用sys.set_asyncgen_hooks()注册此终结器When first iterated over, an asynchronous generator-iterator will store the registered finalizer to be called upon finalization. 当第一次迭代时,异步生成器迭代器将存储注册的终结器,以便在终结时调用。For a reference example of a finalizer method see the implementation of asyncio.Loop.shutdown_asyncgens in Lib/asyncio/base_events.py.有关终结器方法的参考示例,请参阅Lib/asyncio/base_events.pyasyncio.Loop.shutdown_asyncgens的实现。

The expression yield from <expr> is a syntax error when used in an asynchronous generator function.在异步生成器函数中使用时,表达式yield from <expr>是一个语法错误。

6.2.9.4. Asynchronous generator-iterator methods异步生成器迭代器方法

This subsection describes the methods of an asynchronous generator iterator, which are used to control the execution of a generator function.本小节描述异步生成器迭代器的方法,这些方法用于控制生成器函数的执行。

coroutineagen.__anext__()

Returns an awaitable which when run starts to execute the asynchronous generator or resumes it at the last executed yield expression. 返回一个waitiable,当run开始执行异步生成器或在最后一个执行的yield表达式处恢复它时,它将开始执行异步生成器。When an asynchronous generator function is resumed with an __anext__() method, the current yield expression always evaluates to None in the returned awaitable, which when run will continue to the next yield expression. 使用__anext__()方法恢复异步生成器函数时,在返回的awaitiable中,当前的yield表达式的计算结果始终为None,运行时将继续到下一个yield表达式。The value of the expression_list of the yield expression is the value of the StopIteration exception raised by the completing coroutine. yield表达式的expression_list的值是完成协同例程引发的StopIteration异常的值。If the asynchronous generator exits without yielding another value, the awaitable instead raises a StopAsyncIteration exception, signalling that the asynchronous iteration has completed.如果异步生成器退出而不产生另一个值,那么等待将引发StopAsyncIteration异常,表明异步迭代已完成。

This method is normally called implicitly by a async for loop.此方法通常由async for循环隐式调用。

coroutineagen.asend(value)

Returns an awaitable which when run resumes the execution of the asynchronous generator. 返回一个等待值,当运行该值时,将恢复异步生成器的执行。As with the send() method for a generator, this “sends” a value into the asynchronous generator function, and the value argument becomes the result of the current yield expression. 与生成器的send()方法一样,这会将值“发送”到异步生成器函数中,并且value参数将成为当前yield表达式的结果。The awaitable returned by the asend() method will return the next value yielded by the generator as the value of the raised StopIteration, or raises StopAsyncIteration if the asynchronous generator exits without yielding another value. asend()方法返回的awaitiable将返回生成器生成的下一个值作为提升的StopIteration的值,如果异步生成器退出而不生成其他值,则将提升StopIterationWhen asend() is called to start the asynchronous generator, it must be called with None as the argument, because there is no yield expression that could receive the value.当调用asend()来启动异步生成器时,必须以None作为参数来调用它,因为没有可以接收该值的yield表达式。

coroutineagen.athrow(type[, value[, traceback]])

Returns an awaitable that raises an exception of type type at the point where the asynchronous generator was paused, and returns the next value yielded by the generator function as the value of the raised StopIteration exception. 返回在异步生成器暂停时引发类型为type的异常的等待,并返回生成器函数生成的下一个值作为引发的StopIteration异常的值。If the asynchronous generator exits without yielding another value, a StopAsyncIteration exception is raised by the awaitable. 如果异步生成器退出而不产生另一个值,则等待的将引发StopAsyncIteration异常。If the generator function does not catch the passed-in exception, or raises a different exception, then when the awaitable is run that exception propagates to the caller of the awaitable.如果生成器函数未捕获传入的异常,或引发其他异常,则当运行waitiable时,该异常会传播到waitiable的调用方。

coroutineagen.aclose()

Returns an awaitable that when run will throw a GeneratorExit into the asynchronous generator function at the point where it was paused. 返回一个等待的值,即运行时将在异步生成器函数暂停的位置向其抛出GeneratorExitIf the asynchronous generator function then exits gracefully, is already closed, or raises GeneratorExit (by not catching the exception), then the returned awaitable will raise a StopIteration exception. 如果异步生成器函数随后正常退出、已关闭或引发GeneratorExit(通过不捕获异常),则返回的awaitable将引发StopIteration异常。Any further awaitables returned by subsequent calls to the asynchronous generator will raise a StopAsyncIteration exception. 后续调用异步生成器返回的任何其他等待项都将引发StopAsyncIteration异常。If the asynchronous generator yields a value, a RuntimeError is raised by the awaitable. 如果异步生成器生成一个值,则等待的将引发RuntimeErrorIf the asynchronous generator raises any other exception, it is propagated to the caller of the awaitable. 如果异步生成器引发任何其他异常,则会将其传播给等待的调用方。If the asynchronous generator has already exited due to an exception or normal exit, then further calls to aclose() will return an awaitable that does nothing.如果异步生成器由于异常或正常退出而已经退出,那么对aclose()的进一步调用将返回一个不执行任何操作的等待。

6.3. Primaries初选

Primaries represent the most tightly bound operations of the language. 初选表示语言中最紧密的运算。Their syntax is:其语法为:


primary ::= atom | attributeref | subscription | slicing | call

6.3.1. Attribute references属性引用

An attribute reference is a primary followed by a period and a name:属性引用是后跟句点和名称的主引用:


attributeref ::= primary "." identifier

The primary must evaluate to an object of a type that supports attribute references, which most objects do. 主对象必须计算为支持属性引用的类型的对象,大多数对象都会这样做。This object is then asked to produce the attribute whose name is the identifier. 然后要求该对象生成名称为标识符的属性。This production can be customized by overriding the __getattr__() method. 可以通过重写__getattr__()方法自定义此产品。If this attribute is not available, the exception AttributeError is raised. 如果此属性不可用,则引发异常AttributeErrorOtherwise, the type and value of the object produced is determined by the object. 否则,生成的对象的类型和值由该对象确定。Multiple evaluations of the same attribute reference may yield different objects.对同一属性引用的多次求值可能会产生不同的对象。

6.3.2. Subscriptions订阅

The subscription of an instance of a container class will generally select an element from the container. 订阅容器类的实例通常会从容器中选择一个元素。The subscription of a generic class will generally return a GenericAlias object.泛型类的订阅通常会返回GenericAlias对象。


subscription ::= primary "[" expression_list "]"

When an object is subscripted, the interpreter will evaluate the primary and the expression list.当一个对象被订阅时,解释器将计算主列表和表达式列表。

The primary must evaluate to an object that supports subscription. primary必须计算为支持订阅的对象。An object may support subscription through defining one or both of __getitem__() and __class_getitem__(). 对象可以通过定义一个或两个__getitem__()__class_getitem__()来支持订阅。When the primary is subscripted, the evaluated result of the expression list will be passed to one of these methods. 当主键被下标时,表达式列表的计算结果将传递给这些方法之一。For more details on when __class_getitem__ is called instead of __getitem__, see __class_getitem__ versus __getitem__.有关何时调用__class_getitem__而不是__getitem__的详细信息,请参阅__class_getitem____getitem__的比较

If the expression list contains at least one comma, it will evaluate to a tuple containing the items of the expression list. 如果表达式列表至少包含一个逗号,它将计算为包含表达式列表项的元组Otherwise, the expression list will evaluate to the value of the list’s sole member.否则,表达式列表将计算为列表唯一成员的值。

For built-in objects, there are two types of objects that support subscription via __getitem__():对于内置对象,有两种类型的对象支持通过__getitem__()进行订阅:

  1. Mappings. 映射。If the primary is a mapping, the expression list must evaluate to an object whose value is one of the keys of the mapping, and the subscription selects the value in the mapping that corresponds to that key. 如果主对象是映射,则表达式列表必须计算为其值为映射键之一的对象,并且订阅会在映射中选择与该键对应的值。An example of a builtin mapping class is the dict class.dict类是内置映射类的一个示例。

  2. Sequences. 序列。If the primary is a sequence, the expression list must evaluate to an int or a slice (as discussed in the following section). 如果primary是一个序列,则表达式列表的计算结果必须为intslice(如下一节所述)。Examples of builtin sequence classes include the str, list and tuple classes.内置序列类的示例包括strlisttuple类。

The formal syntax makes no special provision for negative indices in sequences. 形式语法对序列中的负索引没有特殊规定。However, built-in sequences all provide a __getitem__() method that interprets negative indices by adding the length of the sequence to the index so that, for example, x[-1] selects the last item of x. 但是,内置序列都提供了一个__getitem__()方法,该方法通过将序列的长度添加到索引来解释负索引,例如,x[-1]选择x的最后一项。The resulting value must be a nonnegative integer less than the number of items in the sequence, and the subscription selects the item whose index is that value (counting from zero). 结果值必须是小于序列中项目数的非负整数,订阅将选择索引为该值的项目(从零开始计数)。Since the support for negative indices and slicing occurs in the object’s __getitem__() method, subclasses overriding this method will need to explicitly add that support.由于对负索引和切片的支持出现在对象的__getitem__()方法中,因此重写此方法的子类将需要显式添加该支持。

A string is a special kind of sequence whose items are characters. string是一种特殊的序列,其项为字符A character is not a separate data type but a string of exactly one character.字符不是单独的数据类型,而是由一个字符组成的字符串。

6.3.3. Slicings切片

A slicing selects a range of items in a sequence object (e.g., a string, tuple or list). 切片选择序列对象中的一系列项目(例如,字符串、元组或列表)。Slicings may be used as expressions or as targets in assignment or del statements. 切片可以用作表达式,也可以用作赋值或del语句中的目标。The syntax for a slicing:切片的语法:


slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= expression | proper_slice
proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
lower_bound ::= expression
upper_bound ::= expression
stride ::= expression

There is ambiguity in the formal syntax here: anything that looks like an expression list also looks like a slice list, so any subscription can be interpreted as a slicing. 这里的形式语法存在歧义:任何看起来像表达式列表的东西也看起来像切片列表,因此任何订阅都可以解释为切片。Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the slice list contains no proper slice).与其使语法进一步复杂化,不如定义在这种情况下,作为订阅的解释优先于作为切片的解释(如果切片列表不包含正确的切片,则为这种情况),从而消除歧义。

The semantics for a slicing are as follows. 切片的语义如下所示。The primary is indexed (using the same __getitem__() method as normal subscription) with a key that is constructed from the slice list, as follows. 使用从切片列表构造的键对主对象进行索引(使用与普通订阅相同的__getitem__()方法),如下所示。If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. 如果切片列表至少包含一个逗号,则键是一个包含切片项转换的元组;否则,单独切片项的转换是关键。The conversion of a slice item that is an expression is that expression. 作为表达式的切片项的转换就是该表达式。The conversion of a proper slice is a slice object (see section The standard type hierarchy) whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions.正确切片的转换是一个切片对象(请参见标准类型层次结构一节),其startstopstep属性分别是作为下限、上限和步幅给定的表达式的值,用无替换缺少的表达式。

6.3.4. Calls调用

A call calls a callable object (e.g., a function) with a possibly empty series of arguments:调用调用具有一系列可能为空的参数的可调用对象(如函数):


call ::= primary "(" [argument_list [","] | comprehension] ")"
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
positional_arguments ::= positional_item ("," positional_item)*
positional_item ::= assignment_expression | "*" expression
starred_and_keywords ::= ("*" expression | keyword_item)
("," "*" expression | "," keyword_item)*
keywords_arguments ::= (keyword_item | "**" expression)
("," keyword_item | "," "**" expression)*
keyword_item ::= identifier "=" expression

An optional trailing comma may be present after the positional and keyword arguments but does not affect the semantics.位置参数和关键字参数后可能会出现可选的尾随逗号,但不会影响语义。

The primary must evaluate to a callable object (user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances, and all objects having a __call__() method are callable). 主对象必须求值为可调用对象(用户定义的函数、内置函数、内置对象的方法、类对象、类实例的方法,以及所有具有__call__()方法的对象都是可调用的)。All argument expressions are evaluated before the call is attempted. 在尝试调用之前,将对所有参数表达式求值。Please refer to section Function definitions for the syntax of formal parameter lists.有关形式参数列表的语法,请参阅函数定义一节。

If keyword arguments are present, they are first converted to positional arguments, as follows. 如果存在关键字参数,则首先将它们转换为位置参数,如下所示。First, a list of unfilled slots is created for the formal parameters. 首先,为形式参数创建一个未填充插槽列表。If there are N positional arguments, they are placed in the first N slots. Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the identifier is the same as the first formal parameter name, the first slot is used, and so on). 如果有N个位置参数,则将它们放置在前N个插槽中。接下来,对于每个关键字参数,使用标识符来确定相应的槽(如果标识符与第一个形式参数名称相同,则使用第一个槽,依此类推)。If the slot is already filled, a TypeError exception is raised. 如果插槽已填充,则引发TypeError异常。Otherwise, the value of the argument is placed in the slot, filling it (even if the expression is None, it fills the slot). 否则,参数的值将放置在槽中,并填充它(即使表达式为None,也会填充槽)。When all arguments have been processed, the slots that are still unfilled are filled with the corresponding default value from the function definition. 处理完所有参数后,仍未填充的插槽将填充函数定义中相应的默认值。(Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don’t specify an argument value for the corresponding slot; this should usually be avoided.) (默认值在定义函数时计算一次;因此,所有调用都将共享一个可变对象,例如用作默认值的列表或字典,而这些调用没有为相应插槽指定参数值;通常应避免这种情况。)If there are any unfilled slots for which no default value is specified, a TypeError exception is raised. 如果没有为任何未填充的插槽指定默认值,则会引发TypeError异常。Otherwise, the list of filled slots is used as the argument list for the call.否则,已填充插槽的列表将用作调用的参数列表。

CPython implementation detail: An implementation may provide built-in functions whose positional parameters do not have names, even if they are ‘named’ for the purpose of documentation, and which therefore cannot be supplied by keyword. 实现可能提供其位置参数没有名称的内置函数,即使它们是为了文档的目的而“命名”的,因此不能通过关键字提供。In CPython, this is the case for functions implemented in C that use PyArg_ParseTuple() to parse their arguments.在CPython中,在C中实现的函数使用PyArg_ParseTuple()解析其参数就是这种情况。

If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax *identifier is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).如果位置参数多于形式参数槽,则引发TypeError异常,除非存在使用语法*identifier的形式参数;在这种情况下,该形式参数接收一个包含多余位置参数的元组(如果没有多余位置参数,则接收一个空元组)。

If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax **identifier is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.如果任何关键字参数与形式参数名称不对应,则引发TypeError异常,除非存在使用语法**identifier的形式参数;在这种情况下,该形式参数接收一个包含多余关键字参数的字典(使用关键字作为键,参数值作为对应值),或者如果没有多余的关键字参数,则接收一个(新的)空字典。

If the syntax *expression appears in the function call, expression must evaluate to an iterable. 如果函数调用中出现语法*expression,则expression的计算结果必须为iterableElements from these iterables are treated as if they were additional positional arguments. 这些iterables中的元素被视为附加的位置参数。For the call f(x1, x2, *y, x3, x4), if y evaluates to a sequence y1, …, yM, this is equivalent to a call with M+4 positional arguments x1, x2, y1, …, yM, x3, x4.对于调用f(x1, x2, *y, x3, x4),如果y的计算结果是序列y1, …,yM,则这相当于使用M+4个位置参数x1x2y1yMx3x4的调用。

A consequence of this is that although the *expression syntax may appear after explicit keyword arguments, it is processed before the keyword arguments (and any **expression arguments – see below). 这样做的结果是,尽管*expression语法可能出现在显式关键字参数之后,但它是在关键字参数之前处理的(以及任何**expression参数-见下文)。So:

>>> def f(a, b):
... print(a, b)
...
>>> f(b=1, *(2,))
2 1
>>> f(a=1, *(2,))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, *(2,))
1 2

It is unusual for both keyword arguments and the *expression syntax to be used in the same call, so in practice this confusion does not arise.在同一个调用中使用关键字参数和*expression语法是不常见的,因此在实践中不会出现这种混淆。

If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. 如果函数调用中出现语法**expression,则expression必须计算为映射,映射的内容将被视为其他关键字参数。If a keyword is already present (as an explicit keyword argument, or from another unpacking), a TypeError exception is raised.如果关键字已经存在(作为显式关键字参数,或来自其他解包),则会引发TypeError异常。

Formal parameters using the syntax *identifier or **identifier cannot be used as positional argument slots or as keyword argument names.使用语法*identifier**identifier的形式参数不能用作位置参数槽或关键字参数名称。

Changed in version 3.5:版本3.5中更改: Function calls accept any number of * and ** unpackings, positional arguments may follow iterable unpackings (*), and keyword arguments may follow dictionary unpackings (**). 函数调用接受任意数量的***解包,位置参数可以在iterable解包(*)之后,关键字参数可以在字典解包(**)之后。Originally proposed by PEP 448.最初由PEP 448提出。

A call always returns some value, possibly None, unless it raises an exception. 调用总是返回一些值,可能是None,除非它引发异常。How this value is computed depends on the type of the callable object.该值的计算方式取决于可调用对象的类型。

If it is—

a user-defined function:用户定义的函数:

The code block for the function is executed, passing it the argument list. 执行函数的代码块,并将参数列表传递给它。The first thing the code block will do is bind the formal parameters to the arguments; this is described in section Function definitions. 代码块要做的第一件事是将形式参数绑定到参数;这在函数定义一节中进行了描述。When the code block executes a return statement, this specifies the return value of the function call.当代码块执行return语句时,这将指定函数调用的返回值。

a built-in function or method:内置函数或方法:

The result is up to the interpreter; see Built-in Functions for the descriptions of built-in functions and methods.结果由解释器决定;有关内置函数和方法的描述,请参阅内置函数

a class object:类对象:

A new instance of that class is returned.将返回该类的新实例。

a class instance method:

The corresponding user-defined function is called, with an argument list that is one longer than the argument list of the call: the instance becomes the first argument.调用相应的用户定义函数,参数列表比调用的参数列表长一个:实例成为第一个参数。

a class instance:类实例:

The class must define a __call__() method; the effect is then the same as if that method was called.类必须定义一个__call__()方法;其效果与调用该方法的效果相同。

6.4. Await expressionawait表达式

Suspend the execution of coroutine on an awaitable object. 暂停在awaitable对象上执行协同例程Can only be used inside a coroutine function.只能在协同例程函数中使用。


await_expr ::= "await" primary

New in version 3.5.版本3.5中新增。

6.5. The power operator幂乘运算符

The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. 幂运算符比其左侧的一元运算符绑定得更紧密;它的绑定没有右侧的一元运算符那么紧密。The syntax is:语法为:


power ::= (await_expr | primary) ["**" u_expr]

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1**2 results in -1.因此,在幂运算符和一元运算符的非穷举序列中,运算符从右向左求值(这并不限制操作数的求值顺序):-1**2得到-1

The power operator has the same semantics as the built-in pow() function, when called with two arguments: it yields its left argument raised to the power of its right argument. 当使用两个参数调用时,幂运算符与内置pow()函数具有相同的语义:它会将其左参数提升为右参数的幂。The numeric arguments are first converted to a common type, and the result is of that type.数值参数首先转换为公共类型,结果就是该类型。

For int operands, the result has the same type as the operands unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. 对于整型操作数,除非第二个参数为负,否则结果的类型与操作数的类型相同;在这种情况下,所有参数都转换为float,并传递一个float结果。For example, 10**2 returns 100, but 10**-2 returns 0.01.例如,10**2返回100,但10**-2返回0.01

Raising 0.0 to a negative power results in a ZeroDivisionError. 0.0幂乘到负幂会导致ZeroDivisionErrorRaising a negative number to a fractional power results in a complex number. 将负数幂乘到分数次幂会产生一个复数(In earlier versions it raised a ValueError.)(在早期版本中,它引发了ValueError。)

This operation can be customized using the special __pow__() method.可以使用特殊的__pow__()方法自定义此操作。

6.6. Unary arithmetic and bitwise operations一元算术和位运算

All unary arithmetic and bitwise operations have the same priority:所有一元算术和位运算具有相同的优先级:


u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr

The unary - (minus) operator yields the negation of its numeric argument; the operation can be overridden with the __neg__() special method.一元-(负)运算符产生其数值参数的反运算;该操作可以用__neg__()特殊方法重写。

The unary + (plus) operator yields its numeric argument unchanged; the operation can be overridden with the __pos__() special method.一元+(加号)运算符不改变其数值参数;可以使用__pos__()特殊方法重写该操作。

The unary ~ (invert) operator yields the bitwise inversion of its integer argument. 一元~(invert)运算符生成其整数参数的按位反转。The bitwise inversion of x is defined as -(x+1). x的位反转定义为-(x+1)It only applies to integral numbers or to custom objects that override the __invert__() special method.它仅适用于整数或重写__invert__()特殊方法的自定义对象。

In all three cases, if the argument does not have the proper type, a TypeError exception is raised.在这三种情况下,如果参数的类型不正确,则会引发TypeError异常。

6.7. Binary arithmetic operations二进制算术运算

The binary arithmetic operations have the conventional priority levels. 二进制算术运算具有传统的优先级。Note that some of these operations also apply to certain non-numeric types. 请注意,其中一些操作也适用于某些非数字类型。Apart from the power operator, there are only two levels, one for multiplicative operators and one for additive operators:除了幂运算符,只有两个级别,一个用于乘法运算符,一个用于加法运算符:


m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@" m_expr |
m_expr "//" u_expr | m_expr "/" u_expr |
m_expr "%" u_expr
a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr

The * (multiplication) operator yields the product of its arguments. *(乘法)运算符生成其参数的乘积。The arguments must either both be numbers, or one argument must be an integer and the other must be a sequence. 参数必须都是数字,或者一个参数必须是整数,另一个参数必须是序列。In the former case, the numbers are converted to a common type and then multiplied together. 在前一种情况下,数字被转换为公共类型,然后相乘在一起。In the latter case, sequence repetition is performed; a negative repetition factor yields an empty sequence.在后一种情况下,执行序列重复;负重复因子产生空序列。

This operation can be customized using the special __mul__() and __rmul__() methods.可以使用特殊的__mul__()__rmul__()方法自定义此操作。

The @ (at) operator is intended to be used for matrix multiplication. @(at)运算符用于矩阵乘法。No builtin Python types implement this operator.没有内置Python类型实现此运算符。

New in version 3.5.版本3.5中新增。

The / (division) and // (floor division) operators yield the quotient of their arguments. /(除法)和//(向下取整除法)运算符生成其参数的商。The numeric arguments are first converted to a common type. 数值参数首先转换为公共类型。Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the ‘floor’ function applied to the result. 整数的除法生成浮点,而整数的下限除法生成整数;结果是数学除法,并对结果应用“floor”函数。Division by zero raises the ZeroDivisionError exception.除以零引发ZeroDivisionError异常。

This operation can be customized using the special __truediv__() and __floordiv__() methods.可以使用特殊的__truediv__()__floordiv__()方法自定义此操作。

The % (modulo) operator yields the remainder from the division of the first argument by the second. %(模)运算符将第一个参数除以第二个参数得到余数。The numeric arguments are first converted to a common type. 数值参数首先转换为公共类型。A zero right argument raises the ZeroDivisionError exception. 零右参数引发ZeroDivisionError异常。The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) 参数可以是浮点数,例如,3.14%0.7等于0.34(因为3.14等于4*0.7+0.34The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand 1.模运算符总是生成与第二个操作数具有相同符号(或零)的结果;结果的绝对值严格小于第二个操作数的绝对值1

The floor division and modulo operators are connected by the following identity: x == (x//y)*y + (x%y). 地板分割运算符和模运算符通过以下等式连接:x == (x//y)*y + (x%y)Floor division and modulo are also connected with the built-in function divmod(): divmod(x, y) == (x//y, x%y). 地板分割和模也与内置函数divmod()连接:divmod(x, y) == (x//y, x%y)2.

In addition to performing the modulo operation on numbers, the % operator is also overloaded by string objects to perform old-style string formatting (also known as interpolation). 除了对数字执行模运算外,%运算符还被字符串对象重载,以执行旧式字符串格式(也称为插值)。The syntax for string formatting is described in the Python Library Reference, section printf-style String Formatting.Python库参考中的printf样式字符串格式一节介绍了字符串格式的语法。

The modulo operation can be customized using the special __mod__() method.可以使用特殊的__mod__()方法自定义运算。

The floor division operator, the modulo operator, and the divmod() function are not defined for complex numbers. 没有为复数定义floor division运算符、modulo运算符和divmod()函数。Instead, convert to a floating point number using the abs() function if appropriate.如果合适,可以使用abs()函数将其转换为浮点数。

The + (addition) operator yields the sum of its arguments. +(加法)运算符生成其参数之和。The arguments must either both be numbers or both be sequences of the same type. 参数必须都是数字或都是相同类型的序列。In the former case, the numbers are converted to a common type and then added together. 在前一种情况下,数字被转换为公共类型,然后加在一起。In the latter case, the sequences are concatenated.在后一种情况下,序列是串联的。

This operation can be customized using the special __add__() and __radd__() methods.可以使用特殊的__add__()__radd__()方法自定义此操作。

The - (subtraction) operator yields the difference of its arguments. -(减法)运算符产生其参数的差。The numeric arguments are first converted to a common type.数值参数首先转换为公共类型。

This operation can be customized using the special __sub__() method.可以使用特殊的__sub__()方法自定义此操作。

6.8. Shifting operations换档操作

The shifting operations have lower priority than the arithmetic operations:移位运算的优先级低于算术运算:


shift_expr ::= a_expr | shift_expr ("<<" | ">>") a_expr

These operators accept integers as arguments. 这些运算符接受整数作为参数。They shift the first argument to the left or right by the number of bits given by the second argument.它们将第一个参数向左或向右移动第二个参数给定的位数。

This operation can be customized using the special __lshift__() and __rshift__() methods.可以使用特殊的__lshift__()__rshift__()方法自定义此操作。

A right shift by n bits is defined as floor division by pow(2,n). n位右移定义为按pow(2,n)进行向下取整除法。A left shift by n bits is defined as multiplication with pow(2,n).左移n位定义为与pow(2,n)相乘。

6.9. Binary bitwise operations二进制位运算

Each of the three bitwise operations has a different priority level:三个按位操作中的每一个都具有不同的优先级:


and_expr ::= shift_expr | and_expr "&" shift_expr
xor_expr ::= and_expr | xor_expr "^" and_expr
or_expr ::= xor_expr | or_expr "|" xor_expr

The & operator yields the bitwise AND of its arguments, which must be integers or one of them must be a custom object overriding __and__() or __rand__() special methods.&运算符生成其参数的按位AND,这些参数必须是整数,或者其中一个必须是重写__and__()__rand__()特殊方法的自定义对象。

The ^ operator yields the bitwise XOR (exclusive OR) of its arguments, which must be integers or one of them must be a custom object overriding __xor__() or __rxor__() special methods.^运算符生成其参数的按位异或(异或),这些参数必须是整数,或者其中一个必须是重写__xor__()__rxor__()特殊方法的自定义对象。

The | operator yields the bitwise (inclusive) OR of its arguments, which must be integers or one of them must be a custom object overriding __or__() or __ror__() special methods.|运算符生成按位(包含)或其参数,这些参数必须是整数,或者其中一个必须是重写__or__()__ror__()特殊方法的自定义对象。

6.10. Comparisons比较

Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. 与C不同,Python中的所有比较操作都具有相同的优先级,比任何算术、移位或按位操作的优先级都低。Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics:同样与C不同的是,像a < b < c这样的表达式具有数学上的常规解释:


comparison ::= or_expr (comp_operator or_expr)*
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
| "is" ["not"] | ["not"] "in"

Comparisons yield boolean values: True or False. 比较产生布尔值:TrueFalseCustom rich comparison methods may return non-boolean values. 自定义富比较方法可能返回非布尔值。In this case Python will call bool() on such value in boolean contexts.在这种情况下,Python将在布尔上下文中对此类值调用bool()

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).可以任意链接比较,例如,x < y <= z等同于x < y and y <= z,但y只计算一次(但在这两种情况下,当x<y为假时,z根本不计算)。

Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.形式上,如果abcyz是表达式,op1op2opN是比较运算符,那么a op1 b op2 c ... y opN z相当于a op1 b and b op2 c and ... y opN z,但每个表达式最多计算一次。

Note that a op1 b op2 c doesn’t imply any kind of comparison between a and c, so that, e.g., x < y > z is perfectly legal (though perhaps not pretty).请注意,a op1 b op2 c并不意味着ac之间存在任何类型的比较,因此,例如,x < y > z是完全合法的(尽管可能并不漂亮)。

6.10.1. Value comparisons值比较

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects do not need to have the same type.运算符<>==>=<=、和!=比较两个对象的值。对象不需要具有相同的类型。

Chapter Objects, values and types states that objects have a value (in addition to type and identity). 对象、值和类型一章指出对象具有值(除了类型和标识之外)。The value of an object is a rather abstract notion in Python: For example, there is no canonical access method for an object’s value. 在Python中,对象的值是一个相当抽象的概念:例如,对象的值没有规范的访问方法。Also, there is no requirement that the value of an object should be constructed in a particular way, e.g. comprised of all its data attributes. 此外,不要求以特定方式构造对象的值,例如由其所有数据属性组成。Comparison operators implement a particular notion of what the value of an object is. 比较运算符实现对象值的特定概念。One can think of them as defining the value of an object indirectly, by means of their comparison implementation.可以将其视为通过比较实现间接定义对象的值。

Because all types are (direct or indirect) subtypes of object, they inherit the default comparison behavior from object. 因为所有类型都是object的(直接或间接)子类型,所以它们继承了object的默认比较行为。Types can customize their comparison behavior by implementing rich comparison methods like __lt__(), described in Basic customization.类型可以通过实现富比较方法(如__lt__())来自定义其比较行为,如基本自定义中所述。

The default behavior for equality comparison (== and !=) is based on the identity of the objects. 相等比较(==!=)的默认行为基于对象的标识。Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. 因此,具有相同身份的实例的相等比较导致相等,而具有不同身份的实例的相等比较导致不相等。A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).这种默认行为的动机是希望所有对象都是自反的(即x is y意味着x==y)。

A default order comparison (<, >, <=, and >=) is not provided; an attempt raises TypeError. 未提供默认有序比较(<><=>=);尝试引发TypeErrorA motivation for this default behavior is the lack of a similar invariant as for equality.这种默认行为的一个动机是缺少与相等类似的不变量。

The behavior of the default equality comparison, that instances with different identities are always unequal, may be in contrast to what types will need that have a sensible definition of object value and value-based equality. 默认相等比较的行为,即具有不同标识的实例总是不相等的,可能与需要对对象值和基于值的相等进行合理定义的类型形成对比。Such types will need to customize their comparison behavior, and in fact, a number of built-in types have done that.这样的类型需要定制它们的比较行为,事实上,许多内置类型已经做到了这一点。

The following list describes the comparison behavior of the most important built-in types.下面的列表描述了最重要的内置类型的比较行为。

  • Numbers of built-in numeric types (Numeric Types — int, float, complex) and of the standard library types fractions.Fraction and decimal.Decimal can be compared within and across their types, with the restriction that complex numbers do not support order comparison. 内置数字类型(数字类型-int、float、complex)和标准库类型fractions.Fractiondecimal.Decimal的数字可以在其类型内和类型之间进行比较,但限制是复数不支持顺序比较。Within the limits of the types involved, they compare mathematically (algorithmically) correct without loss of precision.在所涉及类型的限制范围内,他们在数学上(算法上)比较正确,而不损失精度。

    The not-a-number values float('NaN') and decimal.Decimal('NaN') are special. 非数字值float('NaN')和decimalDecimal('NaN')是特殊的。Any ordered comparison of a number to a not-a-number value is false. 数字与非数字值的任何有序比较都是falseA counter-intuitive implication is that not-a-number values are not equal to themselves. 一个违反直觉的暗示是,非数字值不等于它们自己。For example, if x = float('NaN'), 3 < x, x < 3 and x == x are all false, while x != x is true. 例如,如果x = float('NaN')3<x,则x<3x==x均为false,而x!=xtrueThis behavior is compliant with IEEE 754.此行为符合IEEE 754。

  • None and NotImplemented are singletons. NoneNotImplemented是单例。PEP 8 advises that comparisons for singletons should always be done with is or is not, never the equality operators.PEP 8建议,应始终使用isis not进行单例比较,而不要使用相等运算符。

  • Binary sequences (instances of bytes or bytearray) can be compared within and across their types. They compare lexicographically using the numeric values of their elements.二进制序列(bytesbytearray的实例)可以在其类型内和类型之间进行比较。他们使用元素的数值按字典进行比较。

  • Strings (instances of str) compare lexicographically using the numerical Unicode code points (the result of the built-in function ord()) of their characters. 字符串(str实例)使用其字符的数字Unicode代码点(内置函数ord()的结果)按字典顺序进行比较。3

    Strings and binary sequences cannot be directly compared.字符串和二进制序列不能直接比较。

  • Sequences (instances of tuple, list, or range) can be compared only within each of their types, with the restriction that ranges do not support order comparison. 序列(tuplelistrange的实例)只能在每个类型内进行比较,限制是范围不支持顺序比较。Equality comparison across these types results in inequality, and ordering comparison across these types raises TypeError.跨这些类型的相等比较会导致不相等,跨这些类型的排序比较会引发TypeError

    Sequences compare lexicographically using comparison of corresponding elements. 序列使用对应元素的比较按词典进行比较。The built-in containers typically assume identical objects are equal to themselves. 内置容器通常假定相同的对象与其自身相等。That lets them bypass equality tests for identical objects to improve performance and to maintain their internal invariants.这使它们能够绕过相同对象的相等性测试,以提高性能并保持其内部不变量。

    Lexicographical comparison between built-in collections works as follows:内置集合之间的词典比较工作如下:

    • For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).对于要比较相等的两个集合,它们必须具有相同的类型,具有相同的长度,并且每对对应的元素必须比较相等(例如,[1,2] == (1,2),因为类型不同)。

    • Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). 支持顺序比较的集合的顺序与其第一个不相等元素相同(例如,[1,2,x] <= [1,2,y]的值与x<=y相同)。If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).如果对应的元素不存在,则首先排序较短的集合(例如,[1,2] < [1,2,3]true)。

  • Mappings (instances of dict) compare equal if and only if they have equal (key, value) pairs. 映射(dict实例)比较相等的当且仅当它们具有相等的(key, value)对时。Equality comparison of the keys and values enforces reflexivity.键和值的相等比较加强了自反性。

    Order comparisons (<, >, <=, and >=) raise TypeError.有序列比较(<><=>=)引发类型错误。

  • Sets (instances of set or frozenset) can be compared within and across their types.集合(setfrozenset的实例)可以在其类型内或跨其类型进行比较。

    They define order comparison operators to mean subset and superset tests. 他们定义了顺序比较运算符来进行均值子集和超集测试。Those relations do not define total orderings (for example, the two sets {1,2} and {2,3} are not equal, nor subsets of one another, nor supersets of one another). 这些关系不定义总序(例如,两个集合{1,2}{2,3}不相等,也不相互子集,也不相互超集)。Accordingly, sets are not appropriate arguments for functions which depend on total ordering (for example, min(), max(), and sorted() produce undefined results given a list of sets as inputs).因此,对于依赖于总排序的函数,集合不是合适的参数(例如,在给定集合列表作为输入的情况下,min()max()sorted()生成未定义的结果)。

    Comparison of sets enforces reflexivity of its elements.集合的比较加强了其元素的自反性。

  • Most other built-in types have no comparison methods implemented, so they inherit the default comparison behavior.大多数其他内置类型没有实现比较方法,因此它们继承默认比较行为。

User-defined classes that customize their comparison behavior should follow some consistency rules, if possible:如果可能,自定义比较行为的用户定义类应遵循一些一致性规则:

  • Equality comparison should be reflexive. 平等比较应该是自反性的。In other words, identical objects should compare equal:换句话说,相同的对象应该比较相等:

    x is y implies 暗示x == y

  • Comparison should be symmetric. 比较应对称。In other words, the following expressions should have the same result:换句话说,以下表达式应具有相同的结果:

    x == y and y == x

    x != y and y != x

    x < y and y > x

    x <= y and y >= x

  • Comparison should be transitive. 比较应该是传递性的。The following (non-exhaustive) examples illustrate that:以下(非详尽)示例说明:

    x > y and y > z implies 暗示x > z

    x < y and y <= z implies 暗示x < z

  • Inverse comparison should result in the boolean negation. 反向比较应导致布尔求反。In other words, the following expressions should have the same result:换句话说,以下表达式应具有相同的结果:

    x == y and not x != y

    x < y and not x >= y (for total ordering)(用于总排序)

    x > y and not x <= y (for total ordering)(用于总排序)

    The last two expressions apply to totally ordered collections (e.g. to sequences, but not to sets or mappings). 最后两个表达式适用于全序集合(例如,适用于序列,但不适用于集合或映射)。See also the total_ordering() decorator.另请参见total_ordering()修饰符。

  • The hash() result should be consistent with equality. hash()结果应与等式一致。Objects that are equal should either have the same hash value, or be marked as unhashable.相等的对象应具有相同的哈希值,或标记为不可损坏。

Python does not enforce these consistency rules. Python不强制执行这些一致性规则。In fact, the not-a-number values are an example for not following these rules.事实上,not-a-number值就是不遵循这些规则的一个例子。

6.10.2. Membership test operations成员资格测试操作

The operators in and not in test for membership. 运算符innot in用于成员资格测试。x in s evaluates to True if x is a member of s, and False otherwise. 如果xs的成员,则x in s计算为True,否则为Falsex not in s returns the negation of x in s. x not in s返回x in s的反运算。All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. 所有内置的序列和集类型都支持此功能,还支持字典;对于字典,in测试字典是否具有给定的键。For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).对于诸如list、tuple、set、frozenset、dict或collections.deque等容器类型,表达式x in y等效于any(x is e or x == e for e in y)

For the string and bytes types, x in y is True if and only if x is a substring of y. 对于字符串和字节类型,当且仅当xy的子字符串时,x in yTrueAn equivalent test is y.find(x) != -1. 等效测试为y.find(x) != -1Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.空字符串始终被视为任何其他字符串的子字符串,因此"" in "abc"将返回True

For user-defined classes which define the __contains__() method, x in y returns True if y.__contains__(x) returns a true value, and False otherwise.对于定义__contains__()方法的用户定义类,如果y.__contains__(x)返回True,则x in y返回True,否则返回False

For user-defined classes which do not define __contains__() but do define __iter__(), x in y is True if some value z, for which the expression x is z or x == z is true, is produced while iterating over y. 对于未定义__contains__()、但定义了__iter__()、且表达式x is z or x == zTrue的用户定义类,如果在迭代y时生成某个值z,则x in yTrueIf an exception is raised during the iteration, it is as if in raised that exception.如果在迭代过程中引发异常,就好像in引发了该异常一样。

Lastly, the old-style iteration protocol is tried: if a class defines __getitem__(), x in y is True if and only if there is a non-negative integer index i such that x is y[i] or x == y[i], and no lower integer index raises the IndexError exception. 最后,尝试了旧式迭代协议:如果类定义了__getitem__(),则当且仅当存在非负整数索引i,使得x is y[i] or x == y[i],并且没有较低的整数索引引发索引器异常时,x in yTrue(If any other exception is raised, it is as if in raised that exception).(如果引发任何其他异常,就好像in引发该异常一样)。

The operator not in is defined to have the inverse truth value of in.运算符not in被定义为具有in的逆真值。

6.10.3. Identity comparisons身份比较

The operators is and is not test for an object’s identity: x is y is true if and only if x and y are the same object. 运算符isis not测试对象的标识:当且仅当xy是同一对象时,x is yTrueAn Object’s identity is determined using the id() function. 使用id()函数确定对象的标识。x is not y yields the inverse truth value. 生成反真值。4

6.11. Boolean operations布尔运算


or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). 在布尔运算的上下文中,以及当控制流语句使用表达式时,以下值被解释为falsefalseNone、所有类型的数字零,以及空字符串和容器(包括字符串、元组、列表、字典、集合和冻结集)。All other values are interpreted as true. 所有其他值都被解释为trueUser-defined objects can customize their truth value by providing a __bool__() method.用户定义的对象可以通过提供__bool__()方法自定义其真值。

The operator not yields True if its argument is false, False otherwise.如果运算符的参数为false,则运算符not产生True,否则将产生False

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.表达式x and y首先计算x;如果xfalse,则返回其值;否则,将计算y并返回结果值。

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.表达式x or y首先计算x;如果xtrue,则返回其值;否则,将计算y并返回结果值。

Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. 请注意,andor都不会将返回的值和类型限制为FalseTrue,而是返回最后计算的参数。This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. 这有时很有用,例如,如果s是一个字符串,如果为空,则应使用默认值替换该字符串,则表达式s or 'foo'将生成所需的值。Because not has to create a new value, it returns a boolean value regardless of the type of its argument (for example, not 'foo' produces False rather than ''.)由于not必须创建新值,因此无论其参数的类型如何,它都会返回布尔值(例如,not 'foo'生成False而不是''。)

6.12. Assignment expressions赋值表达式


assignment_expression ::= [identifier ":="] expression

An assignment expression (sometimes also called a “named expression” or “walrus”) assigns an expression to an identifier, while also returning the value of the expression.赋值表达式(有时也称为“命名表达式”或“walrus”)将expression赋值给identifier,同时还返回expression的值。

One common use case is when handling matched regular expressions:处理匹配的正则表达式时有一个常见的用例:

if matching := pattern.search(data):
do_something(matching)

Or, when processing a file stream in chunks:或者,当以块的形式处理文件流时:

while chunk := file.read(9000):
process(chunk)

New in version 3.8.版本3.8中新增。See PEP 572 for more details about assignment expressions.有关赋值表达式的更多详细信息,请参阅PEP 572

6.13. Conditional expressions条件表达式


conditional_expression ::= or_test ["if" or_test "else" expression]
expression ::= conditional_expression | lambda_expr

Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations.在所有Python操作中,条件表达式(有时称为“三元运算符”)的优先级最低。

The expression x if C else y first evaluates the condition, C rather than x. 表达式x if C else y首先计算条件C而不是xIf C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.如果Ctrue,则计算x并返回其值;否则,将计算y并返回其值。

See PEP 308 for more details about conditional expressions.有关条件表达式的更多详细信息,请参阅PEP 308

6.14. Lambdas兰姆达


lambda_expr ::= "lambda" [parameter_list] ":" expression

Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. Lambda表达式(有时称为Lambda表单)用于创建匿名函数。The expression lambda parameters: expression yields a function object. 表达式lambda parameters: expression生成函数对象。The unnamed object behaves like a function object defined with:未命名对象的行为类似于使用以下定义的函数对象:

def <lambda>(parameters):
return expression

See section Function definitions for the syntax of parameter lists. 有关参数列表的语法,请参阅函数定义一节。Note that functions created with lambda expressions cannot contain statements or annotations.请注意,使用lambda表达式创建的函数不能包含语句或注释。

6.15. Expression lists表达式列表


expression_list ::= expression ("," expression)* [","]
starred_list ::= starred_item ("," starred_item)* [","]
starred_expression ::= expression | (starred_item ",")* [starred_item]
starred_item ::= assignment_expression | "*" or_expr

Except when part of a list or set display, an expression list containing at least one comma yields a tuple. 除非显示列表或集合的一部分,否则包含至少一个逗号的表达式列表将生成元组。The length of the tuple is the number of expressions in the list. 元组的长度是列表中表达式的数量。The expressions are evaluated from left to right.表达式从左到右求值。

An asterisk * denotes iterable unpacking. 星号*表示可迭代拆箱Its operand must be an iterable. 其操作数必须是iterableThe iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.iterable被扩展为一系列项,这些项包含在解包站点的新元组、列表或集合中。

New in version 3.5.版本3.5中新增。Iterable unpacking in expression lists, originally proposed by PEP 448.Iterable在表达式列表中解包,最初由PEP 448提出。

The trailing comma is required only to create a single tuple (a.k.a. a singleton); it is optional in all other cases. 只有创建一个元组(即单元组)时才需要尾部逗号;在所有其他情况下,它都是可选的。A single expression without a trailing comma doesn’t create a tuple, but rather yields the value of that expression. 没有尾随逗号的单个表达式不会创建元组,而是生成该表达式的值。(To create an empty tuple, use an empty pair of parentheses:(要创建空元组,请使用一对空括号: ().)

6.16. Evaluation order评估顺序

Python evaluates expressions from left to right. Python从左到右计算表达式。Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.请注意,在计算赋值时,右侧的求值先于左侧。

In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:在以下行中,表达式将按其后缀的算术顺序求值:

expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2

6.17. Operator precedence运算符优先级

The following table summarizes the operator precedence in Python, from highest precedence (most binding) to lowest precedence (least binding). 下表总结了Python中运算符的优先级,从最高优先级(最大绑定)到最低优先级(最小绑定)。Operators in the same box have the same precedence. 同一框中的运算符具有相同的优先级。Unless the syntax is explicitly given, operators are binary. 除非明确给出语法,否则运算符是二进制的。Operators in the same box group left to right (except for exponentiation, which groups from right to left).同一框中的运算符从左到右分组(指数运算除外,指数运算从右到左分组)。

Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.请注意,比较、成员资格测试和身份测试都具有相同的优先级,并具有从左到右的链接功能,如比较部分所述。

Operator运算符

Description描述

(expressions...),

[expressions...], {key: value...}, {expressions...}

Binding or parenthesized expression, list display, dictionary display, set display绑定或括号表达式、列表显示、字典显示、集合显示

x[index], x[index:index], x(arguments...), x.attribute

Subscription, slicing, call, attribute reference订阅、切片、调用、属性引用

await x

Await expression等待表达式

**

Exponentiation 指数化5

+x, -x, ~x

Positive, negative, bitwise NOT正、负、按位NOT

*, @, /, //, %

Multiplication, matrix multiplication, division, floor division, remainder 乘法、矩阵乘法、除法、地板除法、余数6

+, -

Addition and subtraction加减法

<<, >>

Shifts

&

Bitwise AND按位与

^

Bitwise XOR按位异或

|

Bitwise OR按位或

in, not in, is, is not, <, <=, >, >=, !=, ==

Comparisons, including membership tests and identity tests比较,包括成员资格测试和身份测试

not x

Boolean NOT按位非

and

Boolean AND布尔与

or

Boolean OR布尔或

ifelse

Conditional expression条件表达式

lambda

Lambda expressionLambda表达式

:=

Assignment expression赋值表达式

Footnotes

1

While abs(x%y) < abs(y) is true mathematically, for floats it may not be true numerically due to roundoff. 虽然abs(x%y) < abs(y)在数学上是真的,但对于浮点数,由于舍入,它在数值上可能不是真的。For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that -1e-100 % 1e100 have the same sign as 1e100, the computed result is -1e-100 + 1e100, which is numerically exactly equal to 1e100. 例如,假设平台上的Python浮点是IEEE 754双精度数字,为了使-1e-100% 1e100具有与1e100相同的符号,计算结果是-1e-100 + 1e100,这在数字上正好等于1e100The function math.fmod() returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100 in this case. Which approach is more appropriate depends on the application.函数math.fmod()返回的结果的符号与第一个参数的符号匹配,因此在本例中返回-1e-100。哪种方法更合适取决于应用程序。

2

If x is very close to an exact integer multiple of y, it’s possible for x//y to be one larger than (x-x%y)//y due to rounding. 如果x非常接近y的精确整数倍,则由于舍入,x//y可能比(x-x%y)//y大一倍。In such cases, Python returns the latter result, in order to preserve that divmod(x,y)[0] * y + x % y be very close to x.在这种情况下,Python返回后一个结果,以保持divmod(x,y)[0] * y + x % y非常接近x

3

The Unicode standard distinguishes between code points (e.g. U+0041) and abstract characters (e.g. “LATIN CAPITAL LETTER A”). Unicode标准区分代码点(如U+0041)和抽象字符(如“拉丁文大写字母A”)。While most abstract characters in Unicode are only represented using one code point, there is a number of abstract characters that can in addition be represented using a sequence of more than one code point. 虽然Unicode中的大多数抽象字符仅使用一个代码点表示,但还有许多抽象字符还可以使用多个代码点的序列表示。For example, the abstract character “LATIN CAPITAL LETTER C WITH CEDILLA” can be represented as a single precomposed character at code position U+00C7, or as a sequence of a base character at code position U+0043 (LATIN CAPITAL LETTER C), followed by a combining character at code position U+0327 (COMBINING CEDILLA).例如,抽象字符“带CEDILLA的拉丁文大写字母C”可以表示为代码位置U+00C7处的单个预合成字符,或表示为代码位置U+0043处的基字符序列(拉丁文大写字母C),后跟代码位置U+0327处的组合字符(组合CEDILLA)。

The comparison operators on strings compare at the level of Unicode code points. 字符串上的比较运算符在Unicode代码点级别进行比较。This may be counter-intuitive to humans. 这可能与人类的直觉相反。For example, "\u00C7" == "\u0043\u0327" is False, even though both strings represent the same abstract character “LATIN CAPITAL LETTER C WITH CEDILLA”.例如,"\u00C7" == "\u0043\u0327"False,即使两个字符串都表示相同的抽象字符“带CEDILLA的拉丁文大写字母C”。

To compare strings at the level of abstract characters (that is, in a way intuitive to humans), use unicodedata.normalize().要在抽象字符级别比较字符串(即,以人类直观的方式),请使用unicodedata.normalize()

4

Due to automatic garbage-collection, free lists, and the dynamic nature of descriptors, you may notice seemingly unusual behaviour in certain uses of the is operator, like those involving comparisons between instance methods, or constants. 由于自动垃圾收集、空闲列表和描述符的动态特性,您可能会注意到is运算符的某些使用中似乎存在异常行为,例如涉及实例方法或常量之间比较的行为。Check their documentation for more info.查看他们的文档以了解更多信息。

5

The power operator ** binds less tightly than an arithmetic or bitwise unary operator on its right, that is, 2**-1 is 0.5.幂运算符**比其右侧的算术或按位一元运算符绑定得更紧密,即2**-10.5

6

The % operator is also used for string formatting; the same precedence applies.%运算符还用于字符串格式;同样的优先级也适用。