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