# 6. 表达式¶

```name ::=  `othername`
```

## 6.1. 算术转换¶

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:

• 如果任一参数为复数，另一参数会被转换为复数；

• 否则，如果任一参数为浮点数，另一参数会被转换为浮点数；

• 否则，两者应该都为整数，不需要进行转换。

## 6.2. 原子¶

“原子”指表达式的最基本构成元素。 最简单的原子是标识符和字面值。 以圆括号、方括号或花括号包括的形式在语法上也被归类为原子。 原子的句法为:

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

### 6.2.2. 字面值¶

Python 支持字符串和字节串字面值，以及几种数字字面值:

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

### 6.2.3. 带圆括号的形式¶

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

An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the rules for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object).

### 6.2.4. 列表、集合与字典的显示¶

• 第一种是显式地列出容器内容

• 第二种是通过一组循环和筛选指令计算出来，称为 推导式

```comprehension ::=  `expression` `comp_for`
comp_for      ::=  [ASYNC] "for" `target_list` "in" `or_test` [`comp_iter`]
comp_iter     ::=  `comp_for` | `comp_if`
comp_if       ::=  "if" `expression_nocond` [`comp_iter`]
```

The comprehension consists of a single expression followed by at least one `for` clause and zero or more `for` or `if` clauses. 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.

Note that the comprehension is executed in a separate scope, so names assigned to in the target list don’t “leak” into the enclosing scope.

Since Python 3.6, in an `async def` function, an `async for` clause may be used to iterate over a asynchronous iterator. 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. If a comprehension contains either `async for` clauses or `await` expressions it is called an asynchronous comprehension. An asynchronous comprehension may suspend the execution of the coroutine function in which it appears. See also PEP 530.

### 6.2.5. 列表显示¶

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

### 6.2.6. 集合显示¶

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

### 6.2.7. 字典显示¶

```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`
```

3.5 新版功能: 拆包到字典显示，最初由 PEP 448 提出。

### 6.2.8. 生成器表达式¶

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

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). However, the leftmost `for` clause is immediately evaluated, so that an error produced by it can be seen before any other possible error in the code that handles the generator expression. Subsequent `for` clauses cannot be evaluated immediately since they may depend on the previous `for` loop. For example: ```(x*y for x in range(10) for y in bar(x))```.

Since Python 3.6, if the generator appears in an `async def` function, then `async for` clauses and `await` expressions are permitted as with an asynchronous comprehension. If a generator expression contains either `async for` clauses or `await` expressions it is called an asynchronous generator expression. An asynchronous generator expression yields a new asynchronous generator object, which is an asynchronous iterator (see 异步迭代器).

### 6.2.9. yield 表达式¶

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

yield 表达式在定义 generator 函数或是 asynchronous generator 的时候才会用到。 因此只能在函数定义的内部使用yield表达式。 在一个函数体内使用 yield 表达式会使这个函数变成一个生成器，并且在一个 `async def` 定义的函数体内使用 yield 表达式会让协程函数变成异步的生成器。 比如说:

```def gen():  # defines a generator function
yield 123

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

`try` 结构中的任何位置都允许yield表达式。如果生成器在(因为引用计数到零或是因为被垃圾回收)销毁之前没有恢复执行，将调用生成器-迭代器的 `close()` 方法. close 方法允许任何挂起的 `finally` 子句执行。

When the underlying iterator is complete, the `value` attribute of the raised `StopIteration` instance becomes the value of the yield expression. It can be either set explicitly when raising `StopIteration`, or automatically when the sub-iterator is a generator (by returning a value from the sub-generator).

PEP 255 - 简单生成器

PEP 342 - 通过增强型生成器实现协程

PEP 380 - 委托给子生成器的语法

The proposal to introduce the `yield_from` syntax, making delegation to sub-generators easy.

PEP 525 - 异步生成器

#### 6.2.9.1. 生成器-迭代器的方法¶

`generator.``__next__`()

`generator.``send`(value)

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

`generator.``close`()

#### 6.2.9.2. 例子¶

```>>> 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.
```

#### 6.2.9.3. 异步生成器函数¶

The presence of a yield expression in a function or method defined using `async def` further defines the function as a asynchronous generator function.

In an asynchronous generator function, yield expressions are allowed anywhere in a `try` construct. 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. 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.

`yield from <expr>` 表达式如果在异步生成器函数中使用会引发语法错误。

#### 6.2.9.4. 异步生成器-迭代器方法¶

coroutine `agen.``__anext__`()

Returns an awaitable which when run starts to execute the asynchronous generator or resumes it at the last executed yield expression. When an asynchronous generator function is resumed with a `__anext__()` method, the current yield expression always evaluates to `None` in the returned awaitable, which when run will continue to the next yield expression. The value of the `expression_list` of the yield expression is the value of the `StopIteration` exception raised by the completing coroutine. If the asynchronous generator exits without yielding another value, the awaitable instead raises an `StopAsyncIteration` exception, signalling that the asynchronous iteration has completed.

coroutine `agen.``asend`(value)

coroutine `agen.``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. If the asynchronous generator exits without yielding another value, an `StopAsyncIteration` exception is raised by the awaitable. 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.

coroutine `agen.``aclose`()

## 6.3. 原型¶

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

### 6.3.1. 属性引用¶

```attributeref ::=  `primary` "." `identifier`
```

### 6.3.2. 抽取¶

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

### 6.3.3. 切片¶

```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`
```

### 6.3.4. 调用¶

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

CPython implementation detail: 某些实现可能提供位置参数没有名称的内置函数，即使它们在文档说明的场合下有“命名”，因此不能以关键字形式提供参数。 在 CPython 中，以 C 编写并使用 `PyArg_ParseTuple()` 来解析其参数的函数实现就属于这种情况。

```>>> 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
```

## 6.4. await 表达式¶

```await_expr ::=  "await" `primary`
```

3.5 新版功能.

## 6.5. 幂运算符¶

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

`0.0` 进行负数幂次运算将导致 `ZeroDivisionError`。 对负数进行分数幂次运算将返回 `complex` 数值。 （在早期版本中这将引发 `ValueError`。）

## 6.6. 一元算术和位运算¶

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

## 6.7. 二元算术运算符¶

```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`
```

3.5 新版功能.

## 6.8. 移位运算¶

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

In the current implementation, the right-hand operand is required to be at most `sys.maxsize`. If the right-hand operand is larger than `sys.maxsize` an `OverflowError` exception is raised.

## 6.9. 二元位运算¶

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

## 6.10. 比较运算¶

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

### 6.10.1. 值比较¶

• 内置数值类型 (数字类型 — int, float, complex) 以及标准库类型 `fractions.Fraction``decimal.Decimal` 可进行类型内部和跨类型的比较，例外限制是复数不支持次序比较。 在类型相关的限制以内，它们会按数学（算法）规则正确进行比较且不会有精度损失。

The not-a-number values `float('NaN')` and `Decimal('NaN')` are special. They are identical to themselves (`x is x` is true) but are not equal to themselves (`x == x` is false). Additionally, comparing any number to a not-a-number value will return `False`. For example, both `3 < float('NaN')` and `float('NaN') < 3` will return `False`.

• 二进制码序列 (`bytes``bytearray` 的实例) 可进行类型内部和跨类型的比较。 它们使用其元素的数字值按字典顺序进行比较。

• 字符串 (`str` 的实例) 使用其字符的 Unicode 码位数字值 (内置函数 `ord()` 的结果) 按字典顺序进行比较。 3

字符串和二进制码序列不能直接比较。

• 序列 (`tuple`, `list``range` 的实例) 只可进行类型内部的比较，range 还有一个限制是不支持次序比较。 以上对象的跨类型一致性比较结果将是不相等，跨类型次序比较将引发 `TypeError`

序列通过相应元素的比较进行字典列比较，并强制规定元素自反射性。

由于强制元素自反射性，多项集的比较将假定对于一个多项集元素 `x`, `x == x` 总是为真。 基于该假设，将首先比较元素标识号，并且仅会对不同元素执行元素比较。 如果元素是自反射的，这种方式会产生与严格元素比较相同的结果。 对于非自反射的元素，结果将不同于严格元素比较，并且可能会令人惊讶：例如当在列表中使用非自反射的非数字值时，将导致以下比较行为:

```>>> nan = float('NaN')
>>> nan is nan
True
>>> nan == nan
False                 <-- the defined non-reflexive behavior of NaN
>>> [nan] == [nan]
True                  <-- list enforces reflexivity and tests identity first
```

内置多项集间的字典序比较规则如下:

• 两个多项集若要相等，它们必须为相同类型、相同长度，并且每对相应的元素都必须相等（例如，`[1,2] == (1,2)` 为假值，因为类型不同）。

• 对于支持次序比较的多项集，排序与其第一个不相等元素的排序相同（例如 `[1,2,x] <= [1,2,y]` 的值与``x <= y`` 相同）。 如果对应元素不存在，较短的多项集排序在前（例如 `[1,2] < [1,2,3]` 为真值）。

• 两个映射 (`dict` 的实例) 若要相等，必须当且仅当它们具有相同的 (键, 值) 对。 键和值的一致性比较强制规定自反射性。

次序比较 (`<`, `>`, `<=``>=`) 将引发 `TypeError`

• 集合 (`set``frozenset` 的实例) 可进行类型内部和跨类型的比较。

它们将比较运算符定义为子集和超集检测。 这类关系没有定义完全排序（例如 `{1,2}``{2,3}` 两个集合不相等，即不为彼此的子集，也不为彼此的超集。 相应地，集合不适宜作为依赖于完全排序的函数的参数（例如如果给出一个集合列表作为 `min()`, `max()``sorted()` 的输入将产生未定义的结果）。

集合的比较强制规定其元素的自反射性。

• 大多数其他内置类型没有实现比较方法，因此它们会继承默认的比较行为。

• 相等比较应该是自反射的。 换句话说，相同的对象比较时应该相等:

`x is y` 意味着 `x == y`

• 比较应该是对称的。 换句话说，下列表达式应该有相同的结果:

`x == y``y == x`

`x != y``y != x`

`x < y``y > x`

`x <= y``y >= x`

• 比较应该是可传递的。 下列（简要的）例子显示了这一点:

`x > y and y > z` 意味着 `x > z`

`x < y and y <= z` 意味着 `x < z`

• 反向比较应该导致布尔值取反。 换句话说，下列表达式应该有相同的结果:

`x == y``not x != y`

`x < y``not x >= y` (对于完全排序)

`x > y``not x <= y` (对于完全排序)

最后两个表达式适用于完全排序的多项集（即序列而非集合或映射）。 另请参阅 `total_ordering()` 装饰器。

• `hash()` 的结果应该与是否相等一致。 相等的对象应该或者具有相同的哈希值，或者标记为不可哈希。

Python 并不强制要求这些一致性规则。 实际上，非数字值就是一个不遵循这些规则的例子。

### 6.10.2. 成员检测运算¶

The operators `in` and `not in` test for membership. ```x in s``` evaluates to `True` if x is a member of s, and `False` otherwise. `x not in s` returns the negation of `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. 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)`.

For user-defined classes which do not define `__contains__()` but do define `__iter__()`, `x in y` is `True` if some value `z` with `x == z` is produced while iterating over `y`. If an exception is raised during the iteration, it is as if `in` raised that exception.

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 == y[i]`, and all lower integer indices do not raise `IndexError` exception. (If any other exception is raised, it is as if `in` raised that exception).

The operator `not in` is defined to have the inverse true value of `in`.

### 6.10.3. 标识号比较¶

The operators `is` and `is not` test for object identity: ```x is y``` is true if and only if x and y are the same object. Object identity is determined using the `id()` function. `x is not y` yields the inverse truth value. 4

## 6.11. 布尔运算¶

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

## 6.12. 条件表达式¶

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

## 6.13. lambda 表达式¶

```lambda_expr        ::=  "lambda" [`parameter_list`] ":" `expression`
lambda_expr_nocond ::=  "lambda" [`parameter_list`] ":" `expression_nocond`
```

lambda 表达式（有时称为 lambda 构型）被用于创建匿名函数。 表达式 `lambda parameters: expression` 会产生一个函数对象 。 该未命名对象的行为类似于用以下方式定义的函数:

```def <lambda>(parameters):
return expression
```

## 6.14. 表达式列表¶

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

3.5 新版功能: 表达式列表中的可迭代对象拆包，最初由 PEP 448 提出。

## 6.15. 求值顺序¶

Python 按从左至右的顺序对表达式求值。 但注意在对赋值操作求值时，右侧会先于左侧被求值。

```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.16. 运算符优先级¶

`lambda`

lambda 表达式

`or`

`and`

`not` `x`

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

`|`

`^`

`&`

`<<`, `>>`

`+`, `-`

`*`, `@`, `/`, `//`, `%`

`+x`, `-x`, `~x`

`**`

`await` `x`

await 表达式

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

`(expressions...)`, `[expressions...]`, `{key: value...}`, `{expressions...}`

Binding or tuple display, list display, dictionary display, set display

1

2

3

Unicode 标准明确区分 码位 (例如 U+0041) 和 抽象字符 (例如 “大写拉丁字母 A”)。 虽然 Unicode 中的大多数抽象字符都只用一个码位来代表，但也存在一些抽象字符可使用由多个码位组成的序列来表示。 例如，抽象字符 “带有下加符的大写拉丁字母 C” 可以用 U+00C7 码位上的单个 预设字符 来表示，也可以用一个 U+0043 码位上的 基础字符 (大写拉丁字母 C) 加上一个 U+0327 码位上的 组合字符 (组合下加符) 组成的序列来表示。

4

5

`%` 运算符也被用于字符串格式化；在此场合下会使用同样的优先级。

6