Expressions
This chapter explains the meaning of the elements of expressions in Python.In this and the following chapters, extended BNF notation will be used to describe syntax, not lexical analysis. 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.Arithmetic Conversions
When a description of an arithmetic operator below uses the phrase “the numeric arguments are converted to a common real type”, this means that the operator implementation for built-in numeric types works as described in the Numeric Types section of the standard library documentation. Some additional rules apply for certain operators and non-numeric operands. Extensions must define their own conversion behavior.Atoms
Atoms are the most basic elements of expressions. The simplest atoms are names or literals. Forms enclosed in parentheses, brackets or braces are also categorized syntactically as atoms.Built-in Constants
The keywordsTrue, False, and None name built-in constants. The token ... names the Ellipsis constant.
Evaluation of these atoms yields the corresponding value.
Identifiers (Names)
An identifier occurring as an atom is a name. 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 aNameError exception.
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 is independent of the syntactical context in which the identifier is used:- The class name, with leading underscores removed and a single leading underscore inserted, is inserted in front of the identifier
- For example, the identifier
__spamoccurring in a class namedFoois transformed to_Foo__spam
Literals
A literal is a textual representation of a value. Python supports numeric, string and bytes literals. Numeric literals consist of a singleNUMBER token, which names an integer, floating-point number, or an imaginary number.
String and bytes literals may consist of several tokens. Format strings and template strings are treated as string literals.
Negative and complex numbers, like
-3 or 3+4.2j, are syntactically not literals, but unary or binary arithmetic operations involving the - or + operator.String Literal Concatenation
Multiple adjacent string or bytes literals are allowed, and their meaning is the same as their concatenation:+ operator may be used.
Literal concatenation can freely mix raw strings, triple-quoted strings, and formatted string literals:
Parenthesized Forms
A parenthesized form is an optional expression list enclosed in parentheses:- If the list contains at least one comma, it yields a tuple
- Otherwise, it yields the single expression that makes up the expression list
Comprehensions
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
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.
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.
Asynchronous Comprehensions
In anasync def function, an async for clause may be used to iterate over an asynchronous iterator. A comprehension in an async def function may consist of either a for or async for clause following the leading expression, and may also use await expressions.
If a comprehension contains async for clauses, or if it contains await expressions or other asynchronous comprehensions, it is called an asynchronous comprehension. An asynchronous comprehension may suspend the execution of the coroutine function in which it appears.
Primaries
Primaries represent the most tightly bound operations of the language. Their syntax is:Attribute References
An attribute reference is a primary followed by a period and a name:Subscriptions and Slicings
The subscription syntax is usually used for selecting an element from a container:- A single expression (simple subscription)
- A slice (slicing)
- Comma-separated expressions or slices (tuple subscription)
- A starred expression (starred subscription)
Simple Subscription
Slicing
A slice is used to extract a portion of a sequence:slice object whose start, stop and step attributes are the results of the expressions between the colons. Any missing expression evaluates to None.
Comma-Separated Subscripts
The subscript can be given as two or more comma-separated expressions or slices:Calls
A call calls a callable object (e.g., a function) with a possibly empty series of arguments:Positional and Keyword Arguments
If keyword arguments are present, they are first converted to positional arguments. For each keyword argument, the identifier is used to determine the corresponding slot. If there are more positional arguments than there are formal parameter slots, aTypeError exception is raised, unless a formal parameter using the syntax *identifier is present. 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.
Unpacking Arguments
If the syntax*expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments:
**expression appears in the function call, expression must evaluate to a mapping. Key/value pairs from this mapping are treated as if they were additional keyword arguments:
Operators
The following sections describe the semantics of operators in Python.Power Operator
The power operator has higher precedence than unary operators on its left; it has lower precedence than unary operators on its right:Unary Operators
The unary- (minus) operator yields the negation of its numeric argument. The unary + (plus) operator yields its numeric argument unchanged. The unary ~ (invert) operator yields the bitwise inversion of its integer argument.
Binary Arithmetic Operators
The binary arithmetic operators are:Comparison Operators
There are eight comparison operations in Python:Boolean Operators
The Boolean operatorsand, or, and not have lower priority than comparison operators:
Membership Test Operators
The operatorsin and not in test for membership:
Identity Comparisons
The operatorsis and is not test for object identity:
Conditional Expressions
Conditional expressions (sometimes called a “ternary operator”) have the form:x is evaluated and returned; otherwise, y is evaluated and returned:
