6. 表达式

本章阐述 Python 表达式元素的含义。

句法注意事项: 在此及之后章节,扩展 BNF 表示法将用于描述句法,而不是词法分析。当 (一种替代) 句法规则拥有形式

name ::=  othername
							

and no semantics are given, the semantics of this form of name are the same as for 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:

  • 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 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:

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

6.2.1. 标识符 (名称)

作为原子出现的标识符是名称。见章节 标识符和关键词 对于词法定义和章节 命名和绑定 对于命名和绑定文档编制。

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 异常。

6.2.1.1. 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 私有名称 of that class.

另请参阅

The class specifications .

More precisely, private names are transformed to a longer form before code is generated for them. If the transformed name is longer than 255 characters, implementation-defined truncation may happen.

The transformation is independent of the syntactical context in which the identifier is used but only the following private identifiers are mangled:

  • Any name used as the name of a variable that is assigned or read or any name of an attribute being accessed.

    The __name__ attribute of nested functions, classes, and type aliases is however not mangled.

  • The name of imported modules, e.g., __spam in import __spam . If the module is part of a package (i.e., its name contains a dot), the name is not mangled, e.g., the __foo in import __foo.bar is not mangled.

  • The name of an imported member, e.g., __f in from spam import __f .

The transformation rule is defined as follows:

  • The class name, with leading underscores removed and a single leading underscore inserted, is inserted in front of the identifier, e.g., the identifier __spam occurring in a class named Foo , _Foo or __Foo is transformed to _Foo__spam .

  • If the class name consists only of underscores, the transformation is the identity, e.g., the identifier __spam occurring in a class named _ or __ is left as is.

6.2.2. 文字

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 文字 了解细节。

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. 括号形式

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

6.2.4. 显示列表、集和字典

For constructing a list, a set or a dictionary Python provides special syntax called “displays”, each of them in two flavors:

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

However, aside from the iterable expression in the leftmost for clause, the comprehension is executed in a separate implicitly nested scope. 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. 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 example: [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.

从 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 表达式。

If a comprehension contains async for clauses, or if it contains await expressions or other asynchronous comprehensions anywhere except the iterable expression in the leftmost for clause, 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 .

Added in version 3.6: Asynchronous comprehensions were introduced.

3.8 版改变: yield and yield from 被禁止用于隐式嵌套作用域内。

3.11 版改变: Asynchronous comprehensions are now allowed inside comprehensions in asynchronous functions. Outer comprehensions implicitly become asynchronous.