1
2.. _expressions:
3
4***********
5Expressions
6***********
7
8.. index:: expression, BNF
9
10This chapter explains the meaning of the elements of expressions in Python.
11
12**Syntax Notes:** In this and the following chapters, extended BNF notation will
13be used to describe syntax, not lexical analysis.  When (one alternative of) a
14syntax rule has the form
15
16.. productionlist:: python-grammar
17   name: `othername`
18
19and no semantics are given, the semantics of this form of ``name`` are the same
20as for ``othername``.
21
22
23.. _conversions:
24
25Arithmetic conversions
26======================
27
28.. index:: pair: arithmetic; conversion
29
30When a description of an arithmetic operator below uses the phrase "the numeric
31arguments are converted to a common type", this means that the operator
32implementation for built-in types works as follows:
33
34* If either argument is a complex number, the other is converted to complex;
35
36* otherwise, if either argument is a floating point number, the other is
37  converted to floating point;
38
39* otherwise, both must be integers and no conversion is necessary.
40
41Some additional rules apply for certain operators (e.g., a string as a left
42argument to the '%' operator).  Extensions must define their own conversion
43behavior.
44
45
46.. _atoms:
47
48Atoms
49=====
50
51.. index:: atom
52
53Atoms are the most basic elements of expressions.  The simplest atoms are
54identifiers or literals.  Forms enclosed in parentheses, brackets or braces are
55also categorized syntactically as atoms.  The syntax for atoms is:
56
57.. productionlist:: python-grammar
58   atom: `identifier` | `literal` | `enclosure`
59   enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display`
60            : | `generator_expression` | `yield_atom`
61
62
63.. _atom-identifiers:
64
65Identifiers (Names)
66-------------------
67
68.. index:: name, identifier
69
70An identifier occurring as an atom is a name.  See section :ref:`identifiers`
71for lexical definition and section :ref:`naming` for documentation of naming and
72binding.
73
74.. index:: exception: NameError
75
76When the name is bound to an object, evaluation of the atom yields that object.
77When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
78exception.
79
80.. index::
81   pair: name; mangling
82   pair: private; names
83
84**Private name mangling:** When an identifier that textually occurs in a class
85definition begins with two or more underscore characters and does not end in two
86or more underscores, it is considered a :dfn:`private name` of that class.
87Private names are transformed to a longer form before code is generated for
88them.  The transformation inserts the class name, with leading underscores
89removed and a single underscore inserted, in front of the name.  For example,
90the identifier ``__spam`` occurring in a class named ``Ham`` will be transformed
91to ``_Ham__spam``.  This transformation is independent of the syntactical
92context in which the identifier is used.  If the transformed name is extremely
93long (longer than 255 characters), implementation defined truncation may happen.
94If the class name consists only of underscores, no transformation is done.
95
96
97.. _atom-literals:
98
99Literals
100--------
101
102.. index:: single: literal
103
104Python supports string and bytes literals and various numeric literals:
105
106.. productionlist:: python-grammar
107   literal: `stringliteral` | `bytesliteral`
108          : | `integer` | `floatnumber` | `imagnumber`
109
110Evaluation of a literal yields an object of the given type (string, bytes,
111integer, floating point number, complex number) with the given value.  The value
112may be approximated in the case of floating point and imaginary (complex)
113literals.  See section :ref:`literals` for details.
114
115.. index::
116   triple: immutable; data; type
117   pair: immutable; object
118
119All literals correspond to immutable data types, and hence the object's identity
120is less important than its value.  Multiple evaluations of literals with the
121same value (either the same occurrence in the program text or a different
122occurrence) may obtain the same object or a different object with the same
123value.
124
125
126.. _parenthesized:
127
128Parenthesized forms
129-------------------
130
131.. index::
132   single: parenthesized form
133   single: () (parentheses); tuple display
134
135A parenthesized form is an optional expression list enclosed in parentheses:
136
137.. productionlist:: python-grammar
138   parenth_form: "(" [`starred_expression`] ")"
139
140A parenthesized expression list yields whatever that expression list yields: if
141the list contains at least one comma, it yields a tuple; otherwise, it yields
142the single expression that makes up the expression list.
143
144.. index:: pair: empty; tuple
145
146An empty pair of parentheses yields an empty tuple object.  Since tuples are
147immutable, the same rules as for literals apply (i.e., two occurrences of the empty
148tuple may or may not yield the same object).
149
150.. index::
151   single: comma
152   single: , (comma)
153
154Note that tuples are not formed by the parentheses, but rather by use of the
155comma operator.  The exception is the empty tuple, for which parentheses *are*
156required --- allowing unparenthesized "nothing" in expressions would cause
157ambiguities and allow common typos to pass uncaught.
158
159
160.. _comprehensions:
161
162Displays for lists, sets and dictionaries
163-----------------------------------------
164
165.. index:: single: comprehensions
166
167For constructing a list, a set or a dictionary Python provides special syntax
168called "displays", each of them in two flavors:
169
170* either the container contents are listed explicitly, or
171
172* they are computed via a set of looping and filtering instructions, called a
173  :dfn:`comprehension`.
174
175.. index::
176   single: for; in comprehensions
177   single: if; in comprehensions
178   single: async for; in comprehensions
179
180Common syntax elements for comprehensions are:
181
182.. productionlist:: python-grammar
183   comprehension: `assignment_expression` `comp_for`
184   comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`]
185   comp_iter: `comp_for` | `comp_if`
186   comp_if: "if" `expression_nocond` [`comp_iter`]
187
188The comprehension consists of a single expression followed by at least one
189:keyword:`!for` clause and zero or more :keyword:`!for` or :keyword:`!if` clauses.
190In this case, the elements of the new container are those that would be produced
191by considering each of the :keyword:`!for` or :keyword:`!if` clauses a block,
192nesting from left to right, and evaluating the expression to produce an element
193each time the innermost block is reached.
194
195However, aside from the iterable expression in the leftmost :keyword:`!for` clause,
196the comprehension is executed in a separate implicitly nested scope. This ensures
197that names assigned to in the target list don't "leak" into the enclosing scope.
198
199The iterable expression in the leftmost :keyword:`!for` clause is evaluated
200directly in the enclosing scope and then passed as an argument to the implicitly
201nested scope. Subsequent :keyword:`!for` clauses and any filter condition in the
202leftmost :keyword:`!for` clause cannot be evaluated in the enclosing scope as
203they may depend on the values obtained from the leftmost iterable. For example:
204``[x*y for x in range(10) for y in range(x, x+10)]``.
205
206To ensure the comprehension always results in a container of the appropriate
207type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly
208nested scope.
209
210.. index::
211   single: await; in comprehensions
212
213Since Python 3.6, in an :keyword:`async def` function, an :keyword:`!async for`
214clause may be used to iterate over a :term:`asynchronous iterator`.
215A comprehension in an :keyword:`!async def` function may consist of either a
216:keyword:`!for` or :keyword:`!async for` clause following the leading
217expression, may contain additional :keyword:`!for` or :keyword:`!async for`
218clauses, and may also use :keyword:`await` expressions.
219If a comprehension contains either :keyword:`!async for` clauses
220or :keyword:`!await` expressions it is called an
221:dfn:`asynchronous comprehension`.  An asynchronous comprehension may
222suspend the execution of the coroutine function in which it appears.
223See also :pep:`530`.
224
225.. versionadded:: 3.6
226   Asynchronous comprehensions were introduced.
227
228.. versionchanged:: 3.8
229   ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
230
231
232.. _lists:
233
234List displays
235-------------
236
237.. index::
238   pair: list; display
239   pair: list; comprehensions
240   pair: empty; list
241   object: list
242   single: [] (square brackets); list expression
243   single: , (comma); expression list
244
245A list display is a possibly empty series of expressions enclosed in square
246brackets:
247
248.. productionlist:: python-grammar
249   list_display: "[" [`starred_list` | `comprehension`] "]"
250
251A list display yields a new list object, the contents being specified by either
252a list of expressions or a comprehension.  When a comma-separated list of
253expressions is supplied, its elements are evaluated from left to right and
254placed into the list object in that order.  When a comprehension is supplied,
255the list is constructed from the elements resulting from the comprehension.
256
257
258.. _set:
259
260Set displays
261------------
262
263.. index::
264   pair: set; display
265   pair: set; comprehensions
266   object: set
267   single: {} (curly brackets); set expression
268   single: , (comma); expression list
269
270A set display is denoted by curly braces and distinguishable from dictionary
271displays by the lack of colons separating keys and values:
272
273.. productionlist:: python-grammar
274   set_display: "{" (`starred_list` | `comprehension`) "}"
275
276A set display yields a new mutable set object, the contents being specified by
277either a sequence of expressions or a comprehension.  When a comma-separated
278list of expressions is supplied, its elements are evaluated from left to right
279and added to the set object.  When a comprehension is supplied, the set is
280constructed from the elements resulting from the comprehension.
281
282An empty set cannot be constructed with ``{}``; this literal constructs an empty
283dictionary.
284
285
286.. _dict:
287
288Dictionary displays
289-------------------
290
291.. index::
292   pair: dictionary; display
293   pair: dictionary; comprehensions
294   key, datum, key/datum pair
295   object: dictionary
296   single: {} (curly brackets); dictionary expression
297   single: : (colon); in dictionary expressions
298   single: , (comma); in dictionary displays
299
300A dictionary display is a possibly empty series of key/datum pairs enclosed in
301curly braces:
302
303.. productionlist:: python-grammar
304   dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
305   key_datum_list: `key_datum` ("," `key_datum`)* [","]
306   key_datum: `expression` ":" `expression` | "**" `or_expr`
307   dict_comprehension: `expression` ":" `expression` `comp_for`
308
309A dictionary display yields a new dictionary object.
310
311If a comma-separated sequence of key/datum pairs is given, they are evaluated
312from left to right to define the entries of the dictionary: each key object is
313used as a key into the dictionary to store the corresponding datum.  This means
314that you can specify the same key multiple times in the key/datum list, and the
315final dictionary's value for that key will be the last one given.
316
317.. index::
318   unpacking; dictionary
319   single: **; in dictionary displays
320
321A double asterisk ``**`` denotes :dfn:`dictionary unpacking`.
322Its operand must be a :term:`mapping`.  Each mapping item is added
323to the new dictionary.  Later values replace values already set by
324earlier key/datum pairs and earlier dictionary unpackings.
325
326.. versionadded:: 3.5
327   Unpacking into dictionary displays, originally proposed by :pep:`448`.
328
329A dict comprehension, in contrast to list and set comprehensions, needs two
330expressions separated with a colon followed by the usual "for" and "if" clauses.
331When the comprehension is run, the resulting key and value elements are inserted
332in the new dictionary in the order they are produced.
333
334.. index:: pair: immutable; object
335           hashable
336
337Restrictions on the types of the key values are listed earlier in section
338:ref:`types`.  (To summarize, the key type should be :term:`hashable`, which excludes
339all mutable objects.)  Clashes between duplicate keys are not detected; the last
340datum (textually rightmost in the display) stored for a given key value
341prevails.
342
343.. versionchanged:: 3.8
344   Prior to Python 3.8, in dict comprehensions, the evaluation order of key
345   and value was not well-defined.  In CPython, the value was evaluated before
346   the key.  Starting with 3.8, the key is evaluated before the value, as
347   proposed by :pep:`572`.
348
349
350.. _genexpr:
351
352Generator expressions
353---------------------
354
355.. index::
356   pair: generator; expression
357   object: generator
358   single: () (parentheses); generator expression
359
360A generator expression is a compact generator notation in parentheses:
361
362.. productionlist:: python-grammar
363   generator_expression: "(" `expression` `comp_for` ")"
364
365A generator expression yields a new generator object.  Its syntax is the same as
366for comprehensions, except that it is enclosed in parentheses instead of
367brackets or curly braces.
368
369Variables used in the generator expression are evaluated lazily when the
370:meth:`~generator.__next__` method is called for the generator object (in the same
371fashion as normal generators).  However, the iterable expression in the
372leftmost :keyword:`!for` clause is immediately evaluated, so that an error
373produced by it will be emitted at the point where the generator expression
374is defined, rather than at the point where the first value is retrieved.
375Subsequent :keyword:`!for` clauses and any filter condition in the leftmost
376:keyword:`!for` clause cannot be evaluated in the enclosing scope as they may
377depend on the values obtained from the leftmost iterable. For example:
378``(x*y for x in range(10) for y in range(x, x+10))``.
379
380The parentheses can be omitted on calls with only one argument.  See section
381:ref:`calls` for details.
382
383To avoid interfering with the expected operation of the generator expression
384itself, ``yield`` and ``yield from`` expressions are prohibited in the
385implicitly defined generator.
386
387If a generator expression contains either :keyword:`!async for`
388clauses or :keyword:`await` expressions it is called an
389:dfn:`asynchronous generator expression`.  An asynchronous generator
390expression returns a new asynchronous generator object,
391which is an asynchronous iterator (see :ref:`async-iterators`).
392
393.. versionadded:: 3.6
394   Asynchronous generator expressions were introduced.
395
396.. versionchanged:: 3.7
397   Prior to Python 3.7, asynchronous generator expressions could
398   only appear in :keyword:`async def` coroutines.  Starting
399   with 3.7, any function can use asynchronous generator expressions.
400
401.. versionchanged:: 3.8
402   ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
403
404
405.. _yieldexpr:
406
407Yield expressions
408-----------------
409
410.. index::
411   keyword: yield
412   keyword: from
413   pair: yield; expression
414   pair: generator; function
415
416.. productionlist:: python-grammar
417   yield_atom: "(" `yield_expression` ")"
418   yield_expression: "yield" [`expression_list` | "from" `expression`]
419
420The yield expression is used when defining a :term:`generator` function
421or an :term:`asynchronous generator` function and
422thus can only be used in the body of a function definition.  Using a yield
423expression in a function's body causes that function to be a generator,
424and using it in an :keyword:`async def` function's body causes that
425coroutine function to be an asynchronous generator. For example::
426
427    def gen():  # defines a generator function
428        yield 123
429
430    async def agen(): # defines an asynchronous generator function
431        yield 123
432
433Due to their side effects on the containing scope, ``yield`` expressions
434are not permitted as part of the implicitly defined scopes used to
435implement comprehensions and generator expressions.
436
437.. versionchanged:: 3.8
438   Yield expressions prohibited in the implicitly nested scopes used to
439   implement comprehensions and generator expressions.
440
441Generator functions are described below, while asynchronous generator
442functions are described separately in section
443:ref:`asynchronous-generator-functions`.
444
445When a generator function is called, it returns an iterator known as a
446generator.  That generator then controls the execution of the generator function.
447The execution starts when one of the generator's methods is called.  At that
448time, the execution proceeds to the first yield expression, where it is
449suspended again, returning the value of :token:`expression_list` to the generator's
450caller.  By suspended, we mean that all local state is retained, including the
451current bindings of local variables, the instruction pointer, the internal
452evaluation stack, and the state of any exception handling.  When the execution
453is resumed by calling one of the
454generator's methods, the function can proceed exactly as if the yield expression
455were just another external call.  The value of the yield expression after
456resuming depends on the method which resumed the execution.  If
457:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or
458the :func:`next` builtin) then the result is :const:`None`.  Otherwise, if
459:meth:`~generator.send` is used, then the result will be the value passed in to
460that method.
461
462.. index:: single: coroutine
463
464All of this makes generator functions quite similar to coroutines; they yield
465multiple times, they have more than one entry point and their execution can be
466suspended.  The only difference is that a generator function cannot control
467where the execution should continue after it yields; the control is always
468transferred to the generator's caller.
469
470Yield expressions are allowed anywhere in a :keyword:`try` construct.  If the
471generator is not resumed before it is
472finalized (by reaching a zero reference count or by being garbage collected),
473the generator-iterator's :meth:`~generator.close` method will be called,
474allowing any pending :keyword:`finally` clauses to execute.
475
476.. index::
477   single: from; yield from expression
478
479When ``yield from <expr>`` is used, the supplied expression must be an
480iterable. The values produced by iterating that iterable are passed directly
481to the caller of the current generator's methods. Any values passed in with
482:meth:`~generator.send` and any exceptions passed in with
483:meth:`~generator.throw` are passed to the underlying iterator if it has the
484appropriate methods.  If this is not the case, then :meth:`~generator.send`
485will raise :exc:`AttributeError` or :exc:`TypeError`, while
486:meth:`~generator.throw` will just raise the passed in exception immediately.
487
488When the underlying iterator is complete, the :attr:`~StopIteration.value`
489attribute of the raised :exc:`StopIteration` instance becomes the value of
490the yield expression. It can be either set explicitly when raising
491:exc:`StopIteration`, or automatically when the subiterator is a generator
492(by returning a value from the subgenerator).
493
494   .. versionchanged:: 3.3
495      Added ``yield from <expr>`` to delegate control flow to a subiterator.
496
497The parentheses may be omitted when the yield expression is the sole expression
498on the right hand side of an assignment statement.
499
500.. seealso::
501
502   :pep:`255` - Simple Generators
503      The proposal for adding generators and the :keyword:`yield` statement to Python.
504
505   :pep:`342` - Coroutines via Enhanced Generators
506      The proposal to enhance the API and syntax of generators, making them
507      usable as simple coroutines.
508
509   :pep:`380` - Syntax for Delegating to a Subgenerator
510      The proposal to introduce the :token:`yield_from` syntax, making delegation
511      to subgenerators easy.
512
513   :pep:`525` - Asynchronous Generators
514      The proposal that expanded on :pep:`492` by adding generator capabilities to
515      coroutine functions.
516
517.. index:: object: generator
518.. _generator-methods:
519
520Generator-iterator methods
521^^^^^^^^^^^^^^^^^^^^^^^^^^
522
523This subsection describes the methods of a generator iterator.  They can
524be used to control the execution of a generator function.
525
526Note that calling any of the generator methods below when the generator
527is already executing raises a :exc:`ValueError` exception.
528
529.. index:: exception: StopIteration
530
531
532.. method:: generator.__next__()
533
534   Starts the execution of a generator function or resumes it at the last
535   executed yield expression.  When a generator function is resumed with a
536   :meth:`~generator.__next__` method, the current yield expression always
537   evaluates to :const:`None`.  The execution then continues to the next yield
538   expression, where the generator is suspended again, and the value of the
539   :token:`expression_list` is returned to :meth:`__next__`'s caller.  If the
540   generator exits without yielding another value, a :exc:`StopIteration`
541   exception is raised.
542
543   This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
544   by the built-in :func:`next` function.
545
546
547.. method:: generator.send(value)
548
549   Resumes the execution and "sends" a value into the generator function.  The
550   *value* argument becomes the result of the current yield expression.  The
551   :meth:`send` method returns the next value yielded by the generator, or
552   raises :exc:`StopIteration` if the generator exits without yielding another
553   value.  When :meth:`send` is called to start the generator, it must be called
554   with :const:`None` as the argument, because there is no yield expression that
555   could receive the value.
556
557
558.. method:: generator.throw(type[, value[, traceback]])
559
560   Raises an exception of type ``type`` at the point where the generator was paused,
561   and returns the next value yielded by the generator function.  If the generator
562   exits without yielding another value, a :exc:`StopIteration` exception is
563   raised.  If the generator function does not catch the passed-in exception, or
564   raises a different exception, then that exception propagates to the caller.
565
566.. index:: exception: GeneratorExit
567
568
569.. method:: generator.close()
570
571   Raises a :exc:`GeneratorExit` at the point where the generator function was
572   paused.  If the generator function then exits gracefully, is already closed,
573   or raises :exc:`GeneratorExit` (by not catching the exception), close
574   returns to its caller.  If the generator yields a value, a
575   :exc:`RuntimeError` is raised.  If the generator raises any other exception,
576   it is propagated to the caller.  :meth:`close` does nothing if the generator
577   has already exited due to an exception or normal exit.
578
579.. index:: single: yield; examples
580
581Examples
582^^^^^^^^
583
584Here is a simple example that demonstrates the behavior of generators and
585generator functions::
586
587   >>> def echo(value=None):
588   ...     print("Execution starts when 'next()' is called for the first time.")
589   ...     try:
590   ...         while True:
591   ...             try:
592   ...                 value = (yield value)
593   ...             except Exception as e:
594   ...                 value = e
595   ...     finally:
596   ...         print("Don't forget to clean up when 'close()' is called.")
597   ...
598   >>> generator = echo(1)
599   >>> print(next(generator))
600   Execution starts when 'next()' is called for the first time.
601   1
602   >>> print(next(generator))
603   None
604   >>> print(generator.send(2))
605   2
606   >>> generator.throw(TypeError, "spam")
607   TypeError('spam',)
608   >>> generator.close()
609   Don't forget to clean up when 'close()' is called.
610
611For examples using ``yield from``, see :ref:`pep-380` in "What's New in
612Python."
613
614.. _asynchronous-generator-functions:
615
616Asynchronous generator functions
617^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
618
619The presence of a yield expression in a function or method defined using
620:keyword:`async def` further defines the function as an
621:term:`asynchronous generator` function.
622
623When an asynchronous generator function is called, it returns an
624asynchronous iterator known as an asynchronous generator object.
625That object then controls the execution of the generator function.
626An asynchronous generator object is typically used in an
627:keyword:`async for` statement in a coroutine function analogously to
628how a generator object would be used in a :keyword:`for` statement.
629
630Calling one of the asynchronous generator's methods returns an
631:term:`awaitable` object, and the execution starts when this object
632is awaited on. At that time, the execution proceeds to the first yield
633expression, where it is suspended again, returning the value of
634:token:`expression_list` to the awaiting coroutine. As with a generator,
635suspension means that all local state is retained, including the
636current bindings of local variables, the instruction pointer, the internal
637evaluation stack, and the state of any exception handling.  When the execution
638is resumed by awaiting on the next object returned by the asynchronous
639generator's methods, the function can proceed exactly as if the yield
640expression were just another external call. The value of the yield expression
641after resuming depends on the method which resumed the execution.  If
642:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
643:meth:`~agen.asend` is used, then the result will be the value passed in to
644that method.
645
646In an asynchronous generator function, yield expressions are allowed anywhere
647in a :keyword:`try` construct. However, if an asynchronous generator is not
648resumed before it is finalized (by reaching a zero reference count or by
649being garbage collected), then a yield expression within a :keyword:`!try`
650construct could result in a failure to execute pending :keyword:`finally`
651clauses.  In this case, it is the responsibility of the event loop or
652scheduler running the asynchronous generator to call the asynchronous
653generator-iterator's :meth:`~agen.aclose` method and run the resulting
654coroutine object, thus allowing any pending :keyword:`!finally` clauses
655to execute.
656
657To take care of finalization, an event loop should define
658a *finalizer* function which takes an asynchronous generator-iterator
659and presumably calls :meth:`~agen.aclose` and executes the coroutine.
660This  *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`.
661When first iterated over, an asynchronous generator-iterator will store the
662registered *finalizer* to be called upon finalization. For a reference example
663of a *finalizer* method see the implementation of
664``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`.
665
666The expression ``yield from <expr>`` is a syntax error when used in an
667asynchronous generator function.
668
669.. index:: object: asynchronous-generator
670.. _asynchronous-generator-methods:
671
672Asynchronous generator-iterator methods
673^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
674
675This subsection describes the methods of an asynchronous generator iterator,
676which are used to control the execution of a generator function.
677
678
679.. index:: exception: StopAsyncIteration
680
681.. coroutinemethod:: agen.__anext__()
682
683   Returns an awaitable which when run starts to execute the asynchronous
684   generator or resumes it at the last executed yield expression.  When an
685   asynchronous generator function is resumed with an :meth:`~agen.__anext__`
686   method, the current yield expression always evaluates to :const:`None` in
687   the returned awaitable, which when run will continue to the next yield
688   expression. The value of the :token:`expression_list` of the yield
689   expression is the value of the :exc:`StopIteration` exception raised by
690   the completing coroutine.  If the asynchronous generator exits without
691   yielding another value, the awaitable instead raises a
692   :exc:`StopAsyncIteration` exception, signalling that the asynchronous
693   iteration has completed.
694
695   This method is normally called implicitly by a :keyword:`async for` loop.
696
697
698.. coroutinemethod:: agen.asend(value)
699
700   Returns an awaitable which when run resumes the execution of the
701   asynchronous generator. As with the :meth:`~generator.send()` method for a
702   generator, this "sends" a value into the asynchronous generator function,
703   and the *value* argument becomes the result of the current yield expression.
704   The awaitable returned by the :meth:`asend` method will return the next
705   value yielded by the generator as the value of the raised
706   :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the
707   asynchronous generator exits without yielding another value.  When
708   :meth:`asend` is called to start the asynchronous
709   generator, it must be called with :const:`None` as the argument,
710   because there is no yield expression that could receive the value.
711
712
713.. coroutinemethod:: agen.athrow(type[, value[, traceback]])
714
715   Returns an awaitable that raises an exception of type ``type`` at the point
716   where the asynchronous generator was paused, and returns the next value
717   yielded by the generator function as the value of the raised
718   :exc:`StopIteration` exception.  If the asynchronous generator exits
719   without yielding another value, a :exc:`StopAsyncIteration` exception is
720   raised by the awaitable.
721   If the generator function does not catch the passed-in exception, or
722   raises a different exception, then when the awaitable is run that exception
723   propagates to the caller of the awaitable.
724
725.. index:: exception: GeneratorExit
726
727
728.. coroutinemethod:: agen.aclose()
729
730   Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
731   the asynchronous generator function at the point where it was paused.
732   If the asynchronous generator function then exits gracefully, is already
733   closed, or raises :exc:`GeneratorExit` (by not catching the exception),
734   then the returned awaitable will raise a :exc:`StopIteration` exception.
735   Any further awaitables returned by subsequent calls to the asynchronous
736   generator will raise a :exc:`StopAsyncIteration` exception.  If the
737   asynchronous generator yields a value, a :exc:`RuntimeError` is raised
738   by the awaitable.  If the asynchronous generator raises any other exception,
739   it is propagated to the caller of the awaitable.  If the asynchronous
740   generator has already exited due to an exception or normal exit, then
741   further calls to :meth:`aclose` will return an awaitable that does nothing.
742
743.. _primaries:
744
745Primaries
746=========
747
748.. index:: single: primary
749
750Primaries represent the most tightly bound operations of the language. Their
751syntax is:
752
753.. productionlist:: python-grammar
754   primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
755
756
757.. _attribute-references:
758
759Attribute references
760--------------------
761
762.. index::
763   pair: attribute; reference
764   single: . (dot); attribute reference
765
766An attribute reference is a primary followed by a period and a name:
767
768.. productionlist:: python-grammar
769   attributeref: `primary` "." `identifier`
770
771.. index::
772   exception: AttributeError
773   object: module
774   object: list
775
776The primary must evaluate to an object of a type that supports attribute
777references, which most objects do.  This object is then asked to produce the
778attribute whose name is the identifier.  This production can be customized by
779overriding the :meth:`__getattr__` method.  If this attribute is not available,
780the exception :exc:`AttributeError` is raised.  Otherwise, the type and value of
781the object produced is determined by the object.  Multiple evaluations of the
782same attribute reference may yield different objects.
783
784
785.. _subscriptions:
786
787Subscriptions
788-------------
789
790.. index::
791   single: subscription
792   single: [] (square brackets); subscription
793
794.. index::
795   object: sequence
796   object: mapping
797   object: string
798   object: tuple
799   object: list
800   object: dictionary
801   pair: sequence; item
802
803A subscription selects an item of a sequence (string, tuple or list) or mapping
804(dictionary) object:
805
806.. productionlist:: python-grammar
807   subscription: `primary` "[" `expression_list` "]"
808
809The primary must evaluate to an object that supports subscription (lists or
810dictionaries for example).  User-defined objects can support subscription by
811defining a :meth:`__getitem__` method.
812
813For built-in objects, there are two types of objects that support subscription:
814
815If the primary is a mapping, the expression list must evaluate to an object
816whose value is one of the keys of the mapping, and the subscription selects the
817value in the mapping that corresponds to that key.  (The expression list is a
818tuple except if it has exactly one item.)
819
820If the primary is a sequence, the expression list must evaluate to an integer
821or a slice (as discussed in the following section).
822
823The formal syntax makes no special provision for negative indices in
824sequences; however, built-in sequences all provide a :meth:`__getitem__`
825method that interprets negative indices by adding the length of the sequence
826to the index (so that ``x[-1]`` selects the last item of ``x``).  The
827resulting value must be a nonnegative integer less than the number of items in
828the sequence, and the subscription selects the item whose index is that value
829(counting from zero). Since the support for negative indices and slicing
830occurs in the object's :meth:`__getitem__` method, subclasses overriding
831this method will need to explicitly add that support.
832
833.. index::
834   single: character
835   pair: string; item
836
837A string's items are characters.  A character is not a separate data type but a
838string of exactly one character.
839
840
841.. _slicings:
842
843Slicings
844--------
845
846.. index::
847   single: slicing
848   single: slice
849   single: : (colon); slicing
850   single: , (comma); slicing
851
852.. index::
853   object: sequence
854   object: string
855   object: tuple
856   object: list
857
858A slicing selects a range of items in a sequence object (e.g., a string, tuple
859or list).  Slicings may be used as expressions or as targets in assignment or
860:keyword:`del` statements.  The syntax for a slicing:
861
862.. productionlist:: python-grammar
863   slicing: `primary` "[" `slice_list` "]"
864   slice_list: `slice_item` ("," `slice_item`)* [","]
865   slice_item: `expression` | `proper_slice`
866   proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
867   lower_bound: `expression`
868   upper_bound: `expression`
869   stride: `expression`
870
871There is ambiguity in the formal syntax here: anything that looks like an
872expression list also looks like a slice list, so any subscription can be
873interpreted as a slicing.  Rather than further complicating the syntax, this is
874disambiguated by defining that in this case the interpretation as a subscription
875takes priority over the interpretation as a slicing (this is the case if the
876slice list contains no proper slice).
877
878.. index::
879   single: start (slice object attribute)
880   single: stop (slice object attribute)
881   single: step (slice object attribute)
882
883The semantics for a slicing are as follows.  The primary is indexed (using the
884same :meth:`__getitem__` method as
885normal subscription) with a key that is constructed from the slice list, as
886follows.  If the slice list contains at least one comma, the key is a tuple
887containing the conversion of the slice items; otherwise, the conversion of the
888lone slice item is the key.  The conversion of a slice item that is an
889expression is that expression.  The conversion of a proper slice is a slice
890object (see section :ref:`types`) whose :attr:`~slice.start`,
891:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
892expressions given as lower bound, upper bound and stride, respectively,
893substituting ``None`` for missing expressions.
894
895
896.. index::
897   object: callable
898   single: call
899   single: argument; call semantics
900   single: () (parentheses); call
901   single: , (comma); argument list
902   single: = (equals); in function calls
903
904.. _calls:
905
906Calls
907-----
908
909A call calls a callable object (e.g., a :term:`function`) with a possibly empty
910series of :term:`arguments <argument>`:
911
912.. productionlist:: python-grammar
913   call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
914   argument_list: `positional_arguments` ["," `starred_and_keywords`]
915                :   ["," `keywords_arguments`]
916                : | `starred_and_keywords` ["," `keywords_arguments`]
917                : | `keywords_arguments`
918   positional_arguments: positional_item ("," positional_item)*
919   positional_item: `assignment_expression` | "*" `expression`
920   starred_and_keywords: ("*" `expression` | `keyword_item`)
921                : ("," "*" `expression` | "," `keyword_item`)*
922   keywords_arguments: (`keyword_item` | "**" `expression`)
923                : ("," `keyword_item` | "," "**" `expression`)*
924   keyword_item: `identifier` "=" `expression`
925
926An optional trailing comma may be present after the positional and keyword arguments
927but does not affect the semantics.
928
929.. index::
930   single: parameter; call semantics
931
932The primary must evaluate to a callable object (user-defined functions, built-in
933functions, methods of built-in objects, class objects, methods of class
934instances, and all objects having a :meth:`__call__` method are callable).  All
935argument expressions are evaluated before the call is attempted.  Please refer
936to section :ref:`function` for the syntax of formal :term:`parameter` lists.
937
938.. XXX update with kwonly args PEP
939
940If keyword arguments are present, they are first converted to positional
941arguments, as follows.  First, a list of unfilled slots is created for the
942formal parameters.  If there are N positional arguments, they are placed in the
943first N slots.  Next, for each keyword argument, the identifier is used to
944determine the corresponding slot (if the identifier is the same as the first
945formal parameter name, the first slot is used, and so on).  If the slot is
946already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
947the argument is placed in the slot, filling it (even if the expression is
948``None``, it fills the slot).  When all arguments have been processed, the slots
949that are still unfilled are filled with the corresponding default value from the
950function definition.  (Default values are calculated, once, when the function is
951defined; thus, a mutable object such as a list or dictionary used as default
952value will be shared by all calls that don't specify an argument value for the
953corresponding slot; this should usually be avoided.)  If there are any unfilled
954slots for which no default value is specified, a :exc:`TypeError` exception is
955raised.  Otherwise, the list of filled slots is used as the argument list for
956the call.
957
958.. impl-detail::
959
960   An implementation may provide built-in functions whose positional parameters
961   do not have names, even if they are 'named' for the purpose of documentation,
962   and which therefore cannot be supplied by keyword.  In CPython, this is the
963   case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
964   parse their arguments.
965
966If there are more positional arguments than there are formal parameter slots, a
967:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
968``*identifier`` is present; in this case, that formal parameter receives a tuple
969containing the excess positional arguments (or an empty tuple if there were no
970excess positional arguments).
971
972If any keyword argument does not correspond to a formal parameter name, a
973:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
974``**identifier`` is present; in this case, that formal parameter receives a
975dictionary containing the excess keyword arguments (using the keywords as keys
976and the argument values as corresponding values), or a (new) empty dictionary if
977there were no excess keyword arguments.
978
979.. index::
980   single: * (asterisk); in function calls
981   single: unpacking; in function calls
982
983If the syntax ``*expression`` appears in the function call, ``expression`` must
984evaluate to an :term:`iterable`.  Elements from these iterables are
985treated as if they were additional positional arguments.  For the call
986``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*,
987this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
988*y1*, ..., *yM*, *x3*, *x4*.
989
990A consequence of this is that although the ``*expression`` syntax may appear
991*after* explicit keyword arguments, it is processed *before* the
992keyword arguments (and any ``**expression`` arguments -- see below).  So::
993
994   >>> def f(a, b):
995   ...     print(a, b)
996   ...
997   >>> f(b=1, *(2,))
998   2 1
999   >>> f(a=1, *(2,))
1000   Traceback (most recent call last):
1001     File "<stdin>", line 1, in <module>
1002   TypeError: f() got multiple values for keyword argument 'a'
1003   >>> f(1, *(2,))
1004   1 2
1005
1006It is unusual for both keyword arguments and the ``*expression`` syntax to be
1007used in the same call, so in practice this confusion does not arise.
1008
1009.. index::
1010   single: **; in function calls
1011
1012If the syntax ``**expression`` appears in the function call, ``expression`` must
1013evaluate to a :term:`mapping`, the contents of which are treated as
1014additional keyword arguments.  If a keyword is already present
1015(as an explicit keyword argument, or from another unpacking),
1016a :exc:`TypeError` exception is raised.
1017
1018Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
1019used as positional argument slots or as keyword argument names.
1020
1021.. versionchanged:: 3.5
1022   Function calls accept any number of ``*`` and ``**`` unpackings,
1023   positional arguments may follow iterable unpackings (``*``),
1024   and keyword arguments may follow dictionary unpackings (``**``).
1025   Originally proposed by :pep:`448`.
1026
1027A call always returns some value, possibly ``None``, unless it raises an
1028exception.  How this value is computed depends on the type of the callable
1029object.
1030
1031If it is---
1032
1033a user-defined function:
1034   .. index::
1035      pair: function; call
1036      triple: user-defined; function; call
1037      object: user-defined function
1038      object: function
1039
1040   The code block for the function is executed, passing it the argument list.  The
1041   first thing the code block will do is bind the formal parameters to the
1042   arguments; this is described in section :ref:`function`.  When the code block
1043   executes a :keyword:`return` statement, this specifies the return value of the
1044   function call.
1045
1046a built-in function or method:
1047   .. index::
1048      pair: function; call
1049      pair: built-in function; call
1050      pair: method; call
1051      pair: built-in method; call
1052      object: built-in method
1053      object: built-in function
1054      object: method
1055      object: function
1056
1057   The result is up to the interpreter; see :ref:`built-in-funcs` for the
1058   descriptions of built-in functions and methods.
1059
1060a class object:
1061   .. index::
1062      object: class
1063      pair: class object; call
1064
1065   A new instance of that class is returned.
1066
1067a class instance method:
1068   .. index::
1069      object: class instance
1070      object: instance
1071      pair: class instance; call
1072
1073   The corresponding user-defined function is called, with an argument list that is
1074   one longer than the argument list of the call: the instance becomes the first
1075   argument.
1076
1077a class instance:
1078   .. index::
1079      pair: instance; call
1080      single: __call__() (object method)
1081
1082   The class must define a :meth:`__call__` method; the effect is then the same as
1083   if that method was called.
1084
1085
1086.. index:: keyword: await
1087.. _await:
1088
1089Await expression
1090================
1091
1092Suspend the execution of :term:`coroutine` on an :term:`awaitable` object.
1093Can only be used inside a :term:`coroutine function`.
1094
1095.. productionlist:: python-grammar
1096   await_expr: "await" `primary`
1097
1098.. versionadded:: 3.5
1099
1100
1101.. _power:
1102
1103The power operator
1104==================
1105
1106.. index::
1107   pair: power; operation
1108   operator: **
1109
1110The power operator binds more tightly than unary operators on its left; it binds
1111less tightly than unary operators on its right.  The syntax is:
1112
1113.. productionlist:: python-grammar
1114   power: (`await_expr` | `primary`) ["**" `u_expr`]
1115
1116Thus, in an unparenthesized sequence of power and unary operators, the operators
1117are evaluated from right to left (this does not constrain the evaluation order
1118for the operands): ``-1**2`` results in ``-1``.
1119
1120The power operator has the same semantics as the built-in :func:`pow` function,
1121when called with two arguments: it yields its left argument raised to the power
1122of its right argument.  The numeric arguments are first converted to a common
1123type, and the result is of that type.
1124
1125For int operands, the result has the same type as the operands unless the second
1126argument is negative; in that case, all arguments are converted to float and a
1127float result is delivered. For example, ``10**2`` returns ``100``, but
1128``10**-2`` returns ``0.01``.
1129
1130Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
1131Raising a negative number to a fractional power results in a :class:`complex`
1132number. (In earlier versions it raised a :exc:`ValueError`.)
1133
1134
1135.. _unary:
1136
1137Unary arithmetic and bitwise operations
1138=======================================
1139
1140.. index::
1141   triple: unary; arithmetic; operation
1142   triple: unary; bitwise; operation
1143
1144All unary arithmetic and bitwise operations have the same priority:
1145
1146.. productionlist:: python-grammar
1147   u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
1148
1149.. index::
1150   single: negation
1151   single: minus
1152   single: operator; - (minus)
1153   single: - (minus); unary operator
1154
1155The unary ``-`` (minus) operator yields the negation of its numeric argument.
1156
1157.. index::
1158   single: plus
1159   single: operator; + (plus)
1160   single: + (plus); unary operator
1161
1162The unary ``+`` (plus) operator yields its numeric argument unchanged.
1163
1164.. index::
1165   single: inversion
1166   operator: ~ (tilde)
1167
1168The unary ``~`` (invert) operator yields the bitwise inversion of its integer
1169argument.  The bitwise inversion of ``x`` is defined as ``-(x+1)``.  It only
1170applies to integral numbers.
1171
1172.. index:: exception: TypeError
1173
1174In all three cases, if the argument does not have the proper type, a
1175:exc:`TypeError` exception is raised.
1176
1177
1178.. _binary:
1179
1180Binary arithmetic operations
1181============================
1182
1183.. index:: triple: binary; arithmetic; operation
1184
1185The binary arithmetic operations have the conventional priority levels.  Note
1186that some of these operations also apply to certain non-numeric types.  Apart
1187from the power operator, there are only two levels, one for multiplicative
1188operators and one for additive operators:
1189
1190.. productionlist:: python-grammar
1191   m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
1192         : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` |
1193         : `m_expr` "%" `u_expr`
1194   a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
1195
1196.. index::
1197   single: multiplication
1198   operator: * (asterisk)
1199
1200The ``*`` (multiplication) operator yields the product of its arguments.  The
1201arguments must either both be numbers, or one argument must be an integer and
1202the other must be a sequence. In the former case, the numbers are converted to a
1203common type and then multiplied together.  In the latter case, sequence
1204repetition is performed; a negative repetition factor yields an empty sequence.
1205
1206.. index::
1207   single: matrix multiplication
1208   operator: @ (at)
1209
1210The ``@`` (at) operator is intended to be used for matrix multiplication.  No
1211builtin Python types implement this operator.
1212
1213.. versionadded:: 3.5
1214
1215.. index::
1216   exception: ZeroDivisionError
1217   single: division
1218   operator: / (slash)
1219   operator: //
1220
1221The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
1222their arguments.  The numeric arguments are first converted to a common type.
1223Division of integers yields a float, while floor division of integers results in an
1224integer; the result is that of mathematical division with the 'floor' function
1225applied to the result.  Division by zero raises the :exc:`ZeroDivisionError`
1226exception.
1227
1228.. index::
1229   single: modulo
1230   operator: % (percent)
1231
1232The ``%`` (modulo) operator yields the remainder from the division of the first
1233argument by the second.  The numeric arguments are first converted to a common
1234type.  A zero right argument raises the :exc:`ZeroDivisionError` exception.  The
1235arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
1236(since ``3.14`` equals ``4*0.7 + 0.34``.)  The modulo operator always yields a
1237result with the same sign as its second operand (or zero); the absolute value of
1238the result is strictly smaller than the absolute value of the second operand
1239[#]_.
1240
1241The floor division and modulo operators are connected by the following
1242identity: ``x == (x//y)*y + (x%y)``.  Floor division and modulo are also
1243connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
1244x%y)``. [#]_.
1245
1246In addition to performing the modulo operation on numbers, the ``%`` operator is
1247also overloaded by string objects to perform old-style string formatting (also
1248known as interpolation).  The syntax for string formatting is described in the
1249Python Library Reference, section :ref:`old-string-formatting`.
1250
1251The floor division operator, the modulo operator, and the :func:`divmod`
1252function are not defined for complex numbers.  Instead, convert to a floating
1253point number using the :func:`abs` function if appropriate.
1254
1255.. index::
1256   single: addition
1257   single: operator; + (plus)
1258   single: + (plus); binary operator
1259
1260The ``+`` (addition) operator yields the sum of its arguments.  The arguments
1261must either both be numbers or both be sequences of the same type.  In the
1262former case, the numbers are converted to a common type and then added together.
1263In the latter case, the sequences are concatenated.
1264
1265.. index::
1266   single: subtraction
1267   single: operator; - (minus)
1268   single: - (minus); binary operator
1269
1270The ``-`` (subtraction) operator yields the difference of its arguments.  The
1271numeric arguments are first converted to a common type.
1272
1273
1274.. _shifting:
1275
1276Shifting operations
1277===================
1278
1279.. index::
1280   pair: shifting; operation
1281   operator: <<
1282   operator: >>
1283
1284The shifting operations have lower priority than the arithmetic operations:
1285
1286.. productionlist:: python-grammar
1287   shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr`
1288
1289These operators accept integers as arguments.  They shift the first argument to
1290the left or right by the number of bits given by the second argument.
1291
1292.. index:: exception: ValueError
1293
1294A right shift by *n* bits is defined as floor division by ``pow(2,n)``.  A left
1295shift by *n* bits is defined as multiplication with ``pow(2,n)``.
1296
1297
1298.. _bitwise:
1299
1300Binary bitwise operations
1301=========================
1302
1303.. index:: triple: binary; bitwise; operation
1304
1305Each of the three bitwise operations has a different priority level:
1306
1307.. productionlist:: python-grammar
1308   and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1309   xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1310   or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1311
1312.. index::
1313   pair: bitwise; and
1314   operator: & (ampersand)
1315
1316The ``&`` operator yields the bitwise AND of its arguments, which must be
1317integers.
1318
1319.. index::
1320   pair: bitwise; xor
1321   pair: exclusive; or
1322   operator: ^ (caret)
1323
1324The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
1325must be integers.
1326
1327.. index::
1328   pair: bitwise; or
1329   pair: inclusive; or
1330   operator: | (vertical bar)
1331
1332The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
1333must be integers.
1334
1335
1336.. _comparisons:
1337
1338Comparisons
1339===========
1340
1341.. index::
1342   single: comparison
1343   pair: C; language
1344   operator: < (less)
1345   operator: > (greater)
1346   operator: <=
1347   operator: >=
1348   operator: ==
1349   operator: !=
1350
1351Unlike C, all comparison operations in Python have the same priority, which is
1352lower than that of any arithmetic, shifting or bitwise operation.  Also unlike
1353C, expressions like ``a < b < c`` have the interpretation that is conventional
1354in mathematics:
1355
1356.. productionlist:: python-grammar
1357   comparison: `or_expr` (`comp_operator` `or_expr`)*
1358   comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1359                : | "is" ["not"] | ["not"] "in"
1360
1361Comparisons yield boolean values: ``True`` or ``False``.
1362
1363.. index:: pair: chaining; comparisons
1364
1365Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1366``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1367cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1368
1369Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1370*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1371to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1372evaluated at most once.
1373
1374Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
1375*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1376pretty).
1377
1378Value comparisons
1379-----------------
1380
1381The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1382values of two objects.  The objects do not need to have the same type.
1383
1384Chapter :ref:`objects` states that objects have a value (in addition to type
1385and identity).  The value of an object is a rather abstract notion in Python:
1386For example, there is no canonical access method for an object's value.  Also,
1387there is no requirement that the value of an object should be constructed in a
1388particular way, e.g. comprised of all its data attributes. Comparison operators
1389implement a particular notion of what the value of an object is.  One can think
1390of them as defining the value of an object indirectly, by means of their
1391comparison implementation.
1392
1393Because all types are (direct or indirect) subtypes of :class:`object`, they
1394inherit the default comparison behavior from :class:`object`.  Types can
1395customize their comparison behavior by implementing
1396:dfn:`rich comparison methods` like :meth:`__lt__`, described in
1397:ref:`customization`.
1398
1399The default behavior for equality comparison (``==`` and ``!=``) is based on
1400the identity of the objects.  Hence, equality comparison of instances with the
1401same identity results in equality, and equality comparison of instances with
1402different identities results in inequality.  A motivation for this default
1403behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1404implies ``x == y``).
1405
1406A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1407an attempt raises :exc:`TypeError`.  A motivation for this default behavior is
1408the lack of a similar invariant as for equality.
1409
1410The behavior of the default equality comparison, that instances with different
1411identities are always unequal, may be in contrast to what types will need that
1412have a sensible definition of object value and value-based equality.  Such
1413types will need to customize their comparison behavior, and in fact, a number
1414of built-in types have done that.
1415
1416The following list describes the comparison behavior of the most important
1417built-in types.
1418
1419* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1420  library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
1421  compared within and across their types, with the restriction that complex
1422  numbers do not support order comparison.  Within the limits of the types
1423  involved, they compare mathematically (algorithmically) correct without loss
1424  of precision.
1425
1426  The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are
1427  special.  Any ordered comparison of a number to a not-a-number value is false.
1428  A counter-intuitive implication is that not-a-number values are not equal to
1429  themselves.  For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3`` and
1430  ``x == x`` are all false, while ``x != x`` is true.  This behavior is
1431  compliant with IEEE 754.
1432
1433* ``None`` and ``NotImplemented`` are singletons.  :PEP:`8` advises that
1434  comparisons for singletons should always be done with ``is`` or ``is not``,
1435  never the equality operators.
1436
1437* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
1438  compared within and across their types.  They compare lexicographically using
1439  the numeric values of their elements.
1440
1441* Strings (instances of :class:`str`) compare lexicographically using the
1442  numerical Unicode code points (the result of the built-in function
1443  :func:`ord`) of their characters. [#]_
1444
1445  Strings and binary sequences cannot be directly compared.
1446
1447* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can
1448  be compared only within each of their types, with the restriction that ranges
1449  do not support order comparison.  Equality comparison across these types
1450  results in inequality, and ordering comparison across these types raises
1451  :exc:`TypeError`.
1452
1453  Sequences compare lexicographically using comparison of corresponding
1454  elements.  The built-in containers typically assume identical objects are
1455  equal to themselves.  That lets them bypass equality tests for identical
1456  objects to improve performance and to maintain their internal invariants.
1457
1458  Lexicographical comparison between built-in collections works as follows:
1459
1460  - For two collections to compare equal, they must be of the same type, have
1461    the same length, and each pair of corresponding elements must compare
1462    equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1463    same).
1464
1465  - Collections that support order comparison are ordered the same as their
1466    first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same
1467    value as ``x <= y``).  If a corresponding element does not exist, the
1468    shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1469    true).
1470
1471* Mappings (instances of :class:`dict`) compare equal if and only if they have
1472  equal `(key, value)` pairs. Equality comparison of the keys and values
1473  enforces reflexivity.
1474
1475  Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
1476
1477* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within
1478  and across their types.
1479
1480  They define order
1481  comparison operators to mean subset and superset tests.  Those relations do
1482  not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}``
1483  are not equal, nor subsets of one another, nor supersets of one
1484  another).  Accordingly, sets are not appropriate arguments for functions
1485  which depend on total ordering (for example, :func:`min`, :func:`max`, and
1486  :func:`sorted` produce undefined results given a list of sets as inputs).
1487
1488  Comparison of sets enforces reflexivity of its elements.
1489
1490* Most other built-in types have no comparison methods implemented, so they
1491  inherit the default comparison behavior.
1492
1493User-defined classes that customize their comparison behavior should follow
1494some consistency rules, if possible:
1495
1496* Equality comparison should be reflexive.
1497  In other words, identical objects should compare equal:
1498
1499    ``x is y`` implies ``x == y``
1500
1501* Comparison should be symmetric.
1502  In other words, the following expressions should have the same result:
1503
1504    ``x == y`` and ``y == x``
1505
1506    ``x != y`` and ``y != x``
1507
1508    ``x < y`` and ``y > x``
1509
1510    ``x <= y`` and ``y >= x``
1511
1512* Comparison should be transitive.
1513  The following (non-exhaustive) examples illustrate that:
1514
1515    ``x > y and y > z`` implies ``x > z``
1516
1517    ``x < y and y <= z`` implies ``x < z``
1518
1519* Inverse comparison should result in the boolean negation.
1520  In other words, the following expressions should have the same result:
1521
1522    ``x == y`` and ``not x != y``
1523
1524    ``x < y`` and ``not x >= y`` (for total ordering)
1525
1526    ``x > y`` and ``not x <= y`` (for total ordering)
1527
1528  The last two expressions apply to totally ordered collections (e.g. to
1529  sequences, but not to sets or mappings). See also the
1530  :func:`~functools.total_ordering` decorator.
1531
1532* The :func:`hash` result should be consistent with equality.
1533  Objects that are equal should either have the same hash value,
1534  or be marked as unhashable.
1535
1536Python does not enforce these consistency rules. In fact, the not-a-number
1537values are an example for not following these rules.
1538
1539
1540.. _in:
1541.. _not in:
1542.. _membership-test-details:
1543
1544Membership test operations
1545--------------------------
1546
1547The operators :keyword:`in` and :keyword:`not in` test for membership.  ``x in
1548s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
1549``x not in s`` returns the negation of ``x in s``.  All built-in sequences and
1550set types support this as well as dictionary, for which :keyword:`!in` tests
1551whether the dictionary has a given key. For container types such as list, tuple,
1552set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
1553to ``any(x is e or x == e for e in y)``.
1554
1555For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
1556substring of *y*.  An equivalent test is ``y.find(x) != -1``.  Empty strings are
1557always considered to be a substring of any other string, so ``"" in "abc"`` will
1558return ``True``.
1559
1560For user-defined classes which define the :meth:`__contains__` method, ``x in
1561y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and
1562``False`` otherwise.
1563
1564For user-defined classes which do not define :meth:`__contains__` but do define
1565:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z``, for which the
1566expression ``x is z or x == z`` is true, is produced while iterating over ``y``.
1567If an exception is raised during the iteration, it is as if :keyword:`in` raised
1568that exception.
1569
1570Lastly, the old-style iteration protocol is tried: if a class defines
1571:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
1572integer index *i* such that ``x is y[i] or x == y[i]``, and no lower integer index
1573raises the :exc:`IndexError` exception.  (If any other exception is raised, it is as
1574if :keyword:`in` raised that exception).
1575
1576.. index::
1577   operator: in
1578   operator: not in
1579   pair: membership; test
1580   object: sequence
1581
1582The operator :keyword:`not in` is defined to have the inverse truth value of
1583:keyword:`in`.
1584
1585.. index::
1586   operator: is
1587   operator: is not
1588   pair: identity; test
1589
1590
1591.. _is:
1592.. _is not:
1593
1594Identity comparisons
1595--------------------
1596
1597The operators :keyword:`is` and :keyword:`is not` test for an object's identity: ``x
1598is y`` is true if and only if *x* and *y* are the same object.  An Object's identity
1599is determined using the :meth:`id` function.  ``x is not y`` yields the inverse
1600truth value. [#]_
1601
1602
1603.. _booleans:
1604.. _and:
1605.. _or:
1606.. _not:
1607
1608Boolean operations
1609==================
1610
1611.. index::
1612   pair: Conditional; expression
1613   pair: Boolean; operation
1614
1615.. productionlist:: python-grammar
1616   or_test: `and_test` | `or_test` "or" `and_test`
1617   and_test: `not_test` | `and_test` "and" `not_test`
1618   not_test: `comparison` | "not" `not_test`
1619
1620In the context of Boolean operations, and also when expressions are used by
1621control flow statements, the following values are interpreted as false:
1622``False``, ``None``, numeric zero of all types, and empty strings and containers
1623(including strings, tuples, lists, dictionaries, sets and frozensets).  All
1624other values are interpreted as true.  User-defined objects can customize their
1625truth value by providing a :meth:`__bool__` method.
1626
1627.. index:: operator: not
1628
1629The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1630otherwise.
1631
1632.. index:: operator: and
1633
1634The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1635returned; otherwise, *y* is evaluated and the resulting value is returned.
1636
1637.. index:: operator: or
1638
1639The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1640returned; otherwise, *y* is evaluated and the resulting value is returned.
1641
1642Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1643they return to ``False`` and ``True``, but rather return the last evaluated
1644argument.  This is sometimes useful, e.g., if ``s`` is a string that should be
1645replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1646the desired value.  Because :keyword:`not` has to create a new value, it
1647returns a boolean value regardless of the type of its argument
1648(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
1649
1650
1651Assignment expressions
1652======================
1653
1654.. productionlist:: python-grammar
1655   assignment_expression: [`identifier` ":="] `expression`
1656
1657An assignment expression (sometimes also called a "named expression" or
1658"walrus") assigns an :token:`expression` to an :token:`identifier`, while also
1659returning the value of the :token:`expression`.
1660
1661One common use case is when handling matched regular expressions:
1662
1663.. code-block:: python
1664
1665   if matching := pattern.search(data):
1666       do_something(matching)
1667
1668Or, when processing a file stream in chunks:
1669
1670.. code-block:: python
1671
1672   while chunk := file.read(9000):
1673       process(chunk)
1674
1675.. versionadded:: 3.8
1676   See :pep:`572` for more details about assignment expressions.
1677
1678
1679.. _if_expr:
1680
1681Conditional expressions
1682=======================
1683
1684.. index::
1685   pair: conditional; expression
1686   pair: ternary; operator
1687   single: if; conditional expression
1688   single: else; conditional expression
1689
1690.. productionlist:: python-grammar
1691   conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1692   expression: `conditional_expression` | `lambda_expr`
1693   expression_nocond: `or_test` | `lambda_expr_nocond`
1694
1695Conditional expressions (sometimes called a "ternary operator") have the lowest
1696priority of all Python operations.
1697
1698The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1699If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
1700evaluated and its value is returned.
1701
1702See :pep:`308` for more details about conditional expressions.
1703
1704
1705.. _lambdas:
1706.. _lambda:
1707
1708Lambdas
1709=======
1710
1711.. index::
1712   pair: lambda; expression
1713   pair: lambda; form
1714   pair: anonymous; function
1715   single: : (colon); lambda expression
1716
1717.. productionlist:: python-grammar
1718   lambda_expr: "lambda" [`parameter_list`] ":" `expression`
1719   lambda_expr_nocond: "lambda" [`parameter_list`] ":" `expression_nocond`
1720
1721Lambda expressions (sometimes called lambda forms) are used to create anonymous
1722functions. The expression ``lambda parameters: expression`` yields a function
1723object.  The unnamed object behaves like a function object defined with:
1724
1725.. code-block:: none
1726
1727   def <lambda>(parameters):
1728       return expression
1729
1730See section :ref:`function` for the syntax of parameter lists.  Note that
1731functions created with lambda expressions cannot contain statements or
1732annotations.
1733
1734
1735.. _exprlists:
1736
1737Expression lists
1738================
1739
1740.. index::
1741   pair: expression; list
1742   single: , (comma); expression list
1743
1744.. productionlist:: python-grammar
1745   expression_list: `expression` ("," `expression`)* [","]
1746   starred_list: `starred_item` ("," `starred_item`)* [","]
1747   starred_expression: `expression` | (`starred_item` ",")* [`starred_item`]
1748   starred_item: `assignment_expression` | "*" `or_expr`
1749
1750.. index:: object: tuple
1751
1752Except when part of a list or set display, an expression list
1753containing at least one comma yields a tuple.  The length of
1754the tuple is the number of expressions in the list.  The expressions are
1755evaluated from left to right.
1756
1757.. index::
1758   pair: iterable; unpacking
1759   single: * (asterisk); in expression lists
1760
1761An asterisk ``*`` denotes :dfn:`iterable unpacking`.  Its operand must be
1762an :term:`iterable`.  The iterable is expanded into a sequence of items,
1763which are included in the new tuple, list, or set, at the site of
1764the unpacking.
1765
1766.. versionadded:: 3.5
1767   Iterable unpacking in expression lists, originally proposed by :pep:`448`.
1768
1769.. index:: pair: trailing; comma
1770
1771The trailing comma is required only to create a single tuple (a.k.a. a
1772*singleton*); it is optional in all other cases.  A single expression without a
1773trailing comma doesn't create a tuple, but rather yields the value of that
1774expression. (To create an empty tuple, use an empty pair of parentheses:
1775``()``.)
1776
1777
1778.. _evalorder:
1779
1780Evaluation order
1781================
1782
1783.. index:: pair: evaluation; order
1784
1785Python evaluates expressions from left to right.  Notice that while evaluating
1786an assignment, the right-hand side is evaluated before the left-hand side.
1787
1788In the following lines, expressions will be evaluated in the arithmetic order of
1789their suffixes::
1790
1791   expr1, expr2, expr3, expr4
1792   (expr1, expr2, expr3, expr4)
1793   {expr1: expr2, expr3: expr4}
1794   expr1 + expr2 * (expr3 - expr4)
1795   expr1(expr2, expr3, *expr4, **expr5)
1796   expr3, expr4 = expr1, expr2
1797
1798
1799.. _operator-summary:
1800
1801Operator precedence
1802===================
1803
1804.. index::
1805   pair: operator; precedence
1806
1807The following table summarizes the operator precedence in Python, from lowest
1808precedence (least binding) to highest precedence (most binding).  Operators in
1809the same box have the same precedence.  Unless the syntax is explicitly given,
1810operators are binary.  Operators in the same box group left to right (except for
1811exponentiation, which groups from right to left).
1812
1813Note that comparisons, membership tests, and identity tests, all have the same
1814precedence and have a left-to-right chaining feature as described in the
1815:ref:`comparisons` section.
1816
1817
1818+-----------------------------------------------+-------------------------------------+
1819| Operator                                      | Description                         |
1820+===============================================+=====================================+
1821| ``:=``                                        | Assignment expression               |
1822+-----------------------------------------------+-------------------------------------+
1823| :keyword:`lambda`                             | Lambda expression                   |
1824+-----------------------------------------------+-------------------------------------+
1825| :keyword:`if <if_expr>` -- :keyword:`!else`   | Conditional expression              |
1826+-----------------------------------------------+-------------------------------------+
1827| :keyword:`or`                                 | Boolean OR                          |
1828+-----------------------------------------------+-------------------------------------+
1829| :keyword:`and`                                | Boolean AND                         |
1830+-----------------------------------------------+-------------------------------------+
1831| :keyword:`not` ``x``                          | Boolean NOT                         |
1832+-----------------------------------------------+-------------------------------------+
1833| :keyword:`in`, :keyword:`not in`,             | Comparisons, including membership   |
1834| :keyword:`is`, :keyword:`is not`, ``<``,      | tests and identity tests            |
1835| ``<=``, ``>``, ``>=``, ``!=``, ``==``         |                                     |
1836+-----------------------------------------------+-------------------------------------+
1837| ``|``                                         | Bitwise OR                          |
1838+-----------------------------------------------+-------------------------------------+
1839| ``^``                                         | Bitwise XOR                         |
1840+-----------------------------------------------+-------------------------------------+
1841| ``&``                                         | Bitwise AND                         |
1842+-----------------------------------------------+-------------------------------------+
1843| ``<<``, ``>>``                                | Shifts                              |
1844+-----------------------------------------------+-------------------------------------+
1845| ``+``, ``-``                                  | Addition and subtraction            |
1846+-----------------------------------------------+-------------------------------------+
1847| ``*``, ``@``, ``/``, ``//``, ``%``            | Multiplication, matrix              |
1848|                                               | multiplication, division, floor     |
1849|                                               | division, remainder [#]_            |
1850+-----------------------------------------------+-------------------------------------+
1851| ``+x``, ``-x``, ``~x``                        | Positive, negative, bitwise NOT     |
1852+-----------------------------------------------+-------------------------------------+
1853| ``**``                                        | Exponentiation [#]_                 |
1854+-----------------------------------------------+-------------------------------------+
1855| :keyword:`await` ``x``                        | Await expression                    |
1856+-----------------------------------------------+-------------------------------------+
1857| ``x[index]``, ``x[index:index]``,             | Subscription, slicing,              |
1858| ``x(arguments...)``, ``x.attribute``          | call, attribute reference           |
1859+-----------------------------------------------+-------------------------------------+
1860| ``(expressions...)``,                         | Binding or parenthesized            |
1861|                                               | expression,                         |
1862| ``[expressions...]``,                         | list display,                       |
1863| ``{key: value...}``,                          | dictionary display,                 |
1864| ``{expressions...}``                          | set display                         |
1865+-----------------------------------------------+-------------------------------------+
1866
1867
1868.. rubric:: Footnotes
1869
1870.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1871   true numerically due to roundoff.  For example, and assuming a platform on which
1872   a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1873   1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1874   1e100``, which is numerically exactly equal to ``1e100``.  The function
1875   :func:`math.fmod` returns a result whose sign matches the sign of the
1876   first argument instead, and so returns ``-1e-100`` in this case. Which approach
1877   is more appropriate depends on the application.
1878
1879.. [#] If x is very close to an exact integer multiple of y, it's possible for
1880   ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding.  In such
1881   cases, Python returns the latter result, in order to preserve that
1882   ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1883
1884.. [#] The Unicode standard distinguishes between :dfn:`code points`
1885   (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
1886   While most abstract characters in Unicode are only represented using one
1887   code point, there is a number of abstract characters that can in addition be
1888   represented using a sequence of more than one code point.  For example, the
1889   abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
1890   as a single :dfn:`precomposed character` at code position U+00C7, or as a
1891   sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
1892   LETTER C), followed by a :dfn:`combining character` at code position U+0327
1893   (COMBINING CEDILLA).
1894
1895   The comparison operators on strings compare at the level of Unicode code
1896   points. This may be counter-intuitive to humans.  For example,
1897   ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1898   represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".
1899
1900   To compare strings at the level of abstract characters (that is, in a way
1901   intuitive to humans), use :func:`unicodedata.normalize`.
1902
1903.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
1904   descriptors, you may notice seemingly unusual behaviour in certain uses of
1905   the :keyword:`is` operator, like those involving comparisons between instance
1906   methods, or constants.  Check their documentation for more info.
1907
1908.. [#] The ``%`` operator is also used for string formatting; the same
1909   precedence applies.
1910
1911.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1912   bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.
1913