blob: fd7df4cfba973b4d91663818337bbdee0547372d [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2.. _expressions:
3
4***********
5Expressions
6***********
7
Georg Brandl4b491312007-08-31 09:22:56 +00008.. index:: expression, BNF
Georg Brandl116aa622007-08-15 14:28:22 +00009
Brett Cannon7603fa02011-01-06 23:08:16 +000010This chapter explains the meaning of the elements of expressions in Python.
Georg Brandl116aa622007-08-15 14:28:22 +000011
Georg Brandl116aa622007-08-15 14:28:22 +000012**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:: *
17 name: `othername`
18
Georg Brandl116aa622007-08-15 14:28:22 +000019and 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
Georg Brandl116aa622007-08-15 14:28:22 +000030When a description of an arithmetic operator below uses the phrase "the numeric
Georg Brandl96593ed2007-09-07 14:15:41 +000031arguments are converted to a common type," this means that the operator
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070032implementation for built-in types works as follows:
Georg Brandl116aa622007-08-15 14:28:22 +000033
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
Georg Brandl96593ed2007-09-07 14:15:41 +000039* otherwise, both must be integers and no conversion is necessary.
Georg Brandl116aa622007-08-15 14:28:22 +000040
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070041Some additional rules apply for certain operators (e.g., a string as a left
42argument to the '%' operator). Extensions must define their own conversion
43behavior.
Georg Brandl116aa622007-08-15 14:28:22 +000044
45
46.. _atoms:
47
48Atoms
49=====
50
Georg Brandl96593ed2007-09-07 14:15:41 +000051.. index:: atom
Georg Brandl116aa622007-08-15 14:28:22 +000052
53Atoms are the most basic elements of expressions. The simplest atoms are
Georg Brandl96593ed2007-09-07 14:15:41 +000054identifiers or literals. Forms enclosed in parentheses, brackets or braces are
55also categorized syntactically as atoms. The syntax for atoms is:
Georg Brandl116aa622007-08-15 14:28:22 +000056
57.. productionlist::
58 atom: `identifier` | `literal` | `enclosure`
Georg Brandl96593ed2007-09-07 14:15:41 +000059 enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display`
60 : | `generator_expression` | `yield_atom`
Georg Brandl116aa622007-08-15 14:28:22 +000061
62
63.. _atom-identifiers:
64
65Identifiers (Names)
66-------------------
67
Georg Brandl96593ed2007-09-07 14:15:41 +000068.. index:: name, identifier
Georg Brandl116aa622007-08-15 14:28:22 +000069
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
Georg Brandldec3b3f2013-04-14 10:13:42 +020088them. 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.
Georg Brandl116aa622007-08-15 14:28:22 +000095
Georg Brandl116aa622007-08-15 14:28:22 +000096
97.. _atom-literals:
98
99Literals
100--------
101
102.. index:: single: literal
103
Georg Brandl96593ed2007-09-07 14:15:41 +0000104Python supports string and bytes literals and various numeric literals:
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000107 literal: `stringliteral` | `bytesliteral`
108 : | `integer` | `floatnumber` | `imagnumber`
Georg Brandl116aa622007-08-15 14:28:22 +0000109
Georg Brandl96593ed2007-09-07 14:15:41 +0000110Evaluation 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)
Georg Brandl116aa622007-08-15 14:28:22 +0000113literals. See section :ref:`literals` for details.
114
115.. index::
116 triple: immutable; data; type
117 pair: immutable; object
118
Terry Jan Reedyead1de22012-02-17 19:56:58 -0500119All 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.
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125
126.. _parenthesized:
127
128Parenthesized forms
129-------------------
130
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300131.. index::
132 single: parenthesized form
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200133 single: () (parentheses); tuple display
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135A parenthesized form is an optional expression list enclosed in parentheses:
136
137.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000138 parenth_form: "(" [`starred_expression`] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000139
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 rules for literals apply (i.e., two occurrences of the empty
148tuple may or may not yield the same object).
149
150.. index::
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300151 single: comma; tuple display
Georg Brandl116aa622007-08-15 14:28:22 +0000152 pair: tuple; display
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200153 single: , (comma); tuple display
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155Note that tuples are not formed by the parentheses, but rather by use of the
156comma operator. The exception is the empty tuple, for which parentheses *are*
157required --- allowing unparenthesized "nothing" in expressions would cause
158ambiguities and allow common typos to pass uncaught.
159
160
Georg Brandl96593ed2007-09-07 14:15:41 +0000161.. _comprehensions:
162
163Displays for lists, sets and dictionaries
164-----------------------------------------
165
166For constructing a list, a set or a dictionary Python provides special syntax
167called "displays", each of them in two flavors:
168
169* either the container contents are listed explicitly, or
170
171* they are computed via a set of looping and filtering instructions, called a
172 :dfn:`comprehension`.
173
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300174.. index::
175 single: for; in comprehensions
176 single: if; in comprehensions
177 single: async for; in comprehensions
178
Georg Brandl96593ed2007-09-07 14:15:41 +0000179Common syntax elements for comprehensions are:
180
181.. productionlist::
182 comprehension: `expression` `comp_for`
Serhiy Storchakad08972f2018-04-11 19:15:51 +0300183 comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`]
Georg Brandl96593ed2007-09-07 14:15:41 +0000184 comp_iter: `comp_for` | `comp_if`
185 comp_if: "if" `expression_nocond` [`comp_iter`]
186
187The comprehension consists of a single expression followed by at least one
188:keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` clauses.
189In this case, the elements of the new container are those that would be produced
190by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
191nesting from left to right, and evaluating the expression to produce an element
192each time the innermost block is reached.
193
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200194However, aside from the iterable expression in the leftmost :keyword:`for` clause,
195the comprehension is executed in a separate implicitly nested scope. This ensures
196that names assigned to in the target list don't "leak" into the enclosing scope.
197
198The iterable expression in the leftmost :keyword:`for` clause is evaluated
199directly in the enclosing scope and then passed as an argument to the implictly
200nested scope. Subsequent :keyword:`for` clauses and any filter condition in the
201leftmost :keyword:`for` clause cannot be evaluated in the enclosing scope as
202they may depend on the values obtained from the leftmost iterable. For example:
203``[x*y for x in range(10) for y in range(x, x+10)]``.
204
205To ensure the comprehension always results in a container of the appropriate
206type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200207nested scope.
Georg Brandl02c30562007-09-07 17:52:53 +0000208
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300209.. index::
210 single: await; in comprehensions
211
Yury Selivanov03660042016-12-15 17:36:05 -0500212Since Python 3.6, in an :keyword:`async def` function, an :keyword:`async for`
213clause may be used to iterate over a :term:`asynchronous iterator`.
214A comprehension in an :keyword:`async def` function may consist of either a
215:keyword:`for` or :keyword:`async for` clause following the leading
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +0200216expression, may contain additional :keyword:`for` or :keyword:`async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500217clauses, and may also use :keyword:`await` expressions.
218If a comprehension contains either :keyword:`async for` clauses
219or :keyword:`await` expressions it is called an
220:dfn:`asynchronous comprehension`. An asynchronous comprehension may
221suspend the execution of the coroutine function in which it appears.
222See also :pep:`530`.
Georg Brandl96593ed2007-09-07 14:15:41 +0000223
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200224.. versionadded:: 3.6
225 Asynchronous comprehensions were introduced.
226
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200227.. versionchanged:: 3.8
228 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200229
230
Georg Brandl116aa622007-08-15 14:28:22 +0000231.. _lists:
232
233List displays
234-------------
235
236.. index::
237 pair: list; display
238 pair: list; comprehensions
Georg Brandl96593ed2007-09-07 14:15:41 +0000239 pair: empty; list
240 object: list
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200241 single: [] (square brackets); list expression
242 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244A list display is a possibly empty series of expressions enclosed in square
245brackets:
246
247.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000248 list_display: "[" [`starred_list` | `comprehension`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Georg Brandl96593ed2007-09-07 14:15:41 +0000250A list display yields a new list object, the contents being specified by either
251a list of expressions or a comprehension. When a comma-separated list of
252expressions is supplied, its elements are evaluated from left to right and
253placed into the list object in that order. When a comprehension is supplied,
254the list is constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256
Georg Brandl96593ed2007-09-07 14:15:41 +0000257.. _set:
Georg Brandl116aa622007-08-15 14:28:22 +0000258
Georg Brandl96593ed2007-09-07 14:15:41 +0000259Set displays
260------------
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300262.. index::
263 pair: set; display
264 object: set
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200265 single: {} (curly brackets); set expression
266 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000267
Georg Brandl96593ed2007-09-07 14:15:41 +0000268A set display is denoted by curly braces and distinguishable from dictionary
269displays by the lack of colons separating keys and values:
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000272 set_display: "{" (`starred_list` | `comprehension`) "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000273
Georg Brandl96593ed2007-09-07 14:15:41 +0000274A set display yields a new mutable set object, the contents being specified by
275either a sequence of expressions or a comprehension. When a comma-separated
276list of expressions is supplied, its elements are evaluated from left to right
277and added to the set object. When a comprehension is supplied, the set is
278constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000279
Georg Brandl528cdb12008-09-21 07:09:51 +0000280An empty set cannot be constructed with ``{}``; this literal constructs an empty
281dictionary.
Christian Heimes78644762008-03-04 23:39:23 +0000282
283
Georg Brandl116aa622007-08-15 14:28:22 +0000284.. _dict:
285
286Dictionary displays
287-------------------
288
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300289.. index::
290 pair: dictionary; display
291 key, datum, key/datum pair
292 object: dictionary
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200293 single: {} (curly brackets); dictionary expression
294 single: : (colon); in dictionary expressions
295 single: , (comma); in dictionary displays
Georg Brandl116aa622007-08-15 14:28:22 +0000296
297A dictionary display is a possibly empty series of key/datum pairs enclosed in
298curly braces:
299
300.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000301 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000302 key_datum_list: `key_datum` ("," `key_datum`)* [","]
Martin Panter0c0da482016-06-12 01:46:50 +0000303 key_datum: `expression` ":" `expression` | "**" `or_expr`
Georg Brandl96593ed2007-09-07 14:15:41 +0000304 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000305
306A dictionary display yields a new dictionary object.
307
Georg Brandl96593ed2007-09-07 14:15:41 +0000308If a comma-separated sequence of key/datum pairs is given, they are evaluated
309from left to right to define the entries of the dictionary: each key object is
310used as a key into the dictionary to store the corresponding datum. This means
311that you can specify the same key multiple times in the key/datum list, and the
312final dictionary's value for that key will be the last one given.
313
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300314.. index::
315 unpacking; dictionary
316 single: **; in dictionary displays
Martin Panter0c0da482016-06-12 01:46:50 +0000317
318A double asterisk ``**`` denotes :dfn:`dictionary unpacking`.
319Its operand must be a :term:`mapping`. Each mapping item is added
320to the new dictionary. Later values replace values already set by
321earlier key/datum pairs and earlier dictionary unpackings.
322
323.. versionadded:: 3.5
324 Unpacking into dictionary displays, originally proposed by :pep:`448`.
325
Georg Brandl96593ed2007-09-07 14:15:41 +0000326A dict comprehension, in contrast to list and set comprehensions, needs two
327expressions separated with a colon followed by the usual "for" and "if" clauses.
328When the comprehension is run, the resulting key and value elements are inserted
329in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000332 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000335:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000336all mutable objects.) Clashes between duplicate keys are not detected; the last
337datum (textually rightmost in the display) stored for a given key value
338prevails.
339
340
Georg Brandl96593ed2007-09-07 14:15:41 +0000341.. _genexpr:
342
343Generator expressions
344---------------------
345
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300346.. index::
347 pair: generator; expression
348 object: generator
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200349 single: () (parentheses); generator expression
Georg Brandl96593ed2007-09-07 14:15:41 +0000350
351A generator expression is a compact generator notation in parentheses:
352
353.. productionlist::
354 generator_expression: "(" `expression` `comp_for` ")"
355
356A generator expression yields a new generator object. Its syntax is the same as
357for comprehensions, except that it is enclosed in parentheses instead of
358brackets or curly braces.
359
360Variables used in the generator expression are evaluated lazily when the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700361:meth:`~generator.__next__` method is called for the generator object (in the same
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200362fashion as normal generators). However, the iterable expression in the
363leftmost :keyword:`for` clause is immediately evaluated, so that an error
364produced by it will be emitted at the point where the generator expression
365is defined, rather than at the point where the first value is retrieved.
366Subsequent :keyword:`for` clauses and any filter condition in the leftmost
367:keyword:`for` clause cannot be evaluated in the enclosing scope as they may
368depend on the values obtained from the leftmost iterable. For example:
369``(x*y for x in range(10) for y in range(x, x+10))``.
Georg Brandl96593ed2007-09-07 14:15:41 +0000370
371The parentheses can be omitted on calls with only one argument. See section
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700372:ref:`calls` for details.
Georg Brandl96593ed2007-09-07 14:15:41 +0000373
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200374To avoid interfering with the expected operation of the generator expression
375itself, ``yield`` and ``yield from`` expressions are prohibited in the
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200376implicitly defined generator.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200377
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400378If a generator expression contains either :keyword:`async for`
379clauses or :keyword:`await` expressions it is called an
380:dfn:`asynchronous generator expression`. An asynchronous generator
381expression returns a new asynchronous generator object,
382which is an asynchronous iterator (see :ref:`async-iterators`).
383
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200384.. versionadded:: 3.6
385 Asynchronous generator expressions were introduced.
386
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400387.. versionchanged:: 3.7
388 Prior to Python 3.7, asynchronous generator expressions could
389 only appear in :keyword:`async def` coroutines. Starting
390 with 3.7, any function can use asynchronous generator expressions.
Georg Brandl96593ed2007-09-07 14:15:41 +0000391
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200392.. versionchanged:: 3.8
393 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200394
395
Georg Brandl116aa622007-08-15 14:28:22 +0000396.. _yieldexpr:
397
398Yield expressions
399-----------------
400
401.. index::
402 keyword: yield
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300403 keyword: from
Georg Brandl116aa622007-08-15 14:28:22 +0000404 pair: yield; expression
405 pair: generator; function
406
407.. productionlist::
408 yield_atom: "(" `yield_expression` ")"
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000409 yield_expression: "yield" [`expression_list` | "from" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000410
Yury Selivanov03660042016-12-15 17:36:05 -0500411The yield expression is used when defining a :term:`generator` function
412or an :term:`asynchronous generator` function and
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500413thus can only be used in the body of a function definition. Using a yield
Yury Selivanov03660042016-12-15 17:36:05 -0500414expression in a function's body causes that function to be a generator,
415and using it in an :keyword:`async def` function's body causes that
416coroutine function to be an asynchronous generator. For example::
417
418 def gen(): # defines a generator function
419 yield 123
420
421 async def agen(): # defines an asynchronous generator function (PEP 525)
422 yield 123
423
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200424Due to their side effects on the containing scope, ``yield`` expressions
425are not permitted as part of the implicitly defined scopes used to
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200426implement comprehensions and generator expressions.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200427
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200428.. versionchanged:: 3.8
429 Yield expressions prohibited in the implicitly nested scopes used to
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200430 implement comprehensions and generator expressions.
431
Yury Selivanov03660042016-12-15 17:36:05 -0500432Generator functions are described below, while asynchronous generator
433functions are described separately in section
434:ref:`asynchronous-generator-functions`.
Georg Brandl116aa622007-08-15 14:28:22 +0000435
436When a generator function is called, it returns an iterator known as a
Guido van Rossumd0150ad2015-05-05 12:02:01 -0700437generator. That generator then controls the execution of the generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000438The execution starts when one of the generator's methods is called. At that
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500439time, the execution proceeds to the first yield expression, where it is
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700440suspended again, returning the value of :token:`expression_list` to the generator's
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500441caller. By suspended, we mean that all local state is retained, including the
Ethan Furman2f825af2015-01-14 22:25:27 -0800442current bindings of local variables, the instruction pointer, the internal
443evaluation stack, and the state of any exception handling. When the execution
444is resumed by calling one of the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500445generator's methods, the function can proceed exactly as if the yield expression
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700446were just another external call. The value of the yield expression after
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500447resuming depends on the method which resumed the execution. If
448:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or
449the :func:`next` builtin) then the result is :const:`None`. Otherwise, if
450:meth:`~generator.send` is used, then the result will be the value passed in to
451that method.
Georg Brandl116aa622007-08-15 14:28:22 +0000452
453.. index:: single: coroutine
454
455All of this makes generator functions quite similar to coroutines; they yield
456multiple times, they have more than one entry point and their execution can be
457suspended. The only difference is that a generator function cannot control
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700458where the execution should continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000459transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000460
Ethan Furman2f825af2015-01-14 22:25:27 -0800461Yield expressions are allowed anywhere in a :keyword:`try` construct. If the
462generator is not resumed before it is
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500463finalized (by reaching a zero reference count or by being garbage collected),
464the generator-iterator's :meth:`~generator.close` method will be called,
465allowing any pending :keyword:`finally` clauses to execute.
Georg Brandl02c30562007-09-07 17:52:53 +0000466
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300467.. index::
468 single: from; yield from expression
469
Nick Coghlan0ed80192012-01-14 14:43:24 +1000470When ``yield from <expr>`` is used, it treats the supplied expression as
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000471a subiterator. All values produced by that subiterator are passed directly
472to the caller of the current generator's methods. Any values passed in with
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300473:meth:`~generator.send` and any exceptions passed in with
474:meth:`~generator.throw` are passed to the underlying iterator if it has the
475appropriate methods. If this is not the case, then :meth:`~generator.send`
476will raise :exc:`AttributeError` or :exc:`TypeError`, while
477:meth:`~generator.throw` will just raise the passed in exception immediately.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000478
479When the underlying iterator is complete, the :attr:`~StopIteration.value`
480attribute of the raised :exc:`StopIteration` instance becomes the value of
481the yield expression. It can be either set explicitly when raising
482:exc:`StopIteration`, or automatically when the sub-iterator is a generator
483(by returning a value from the sub-generator).
484
Nick Coghlan0ed80192012-01-14 14:43:24 +1000485 .. versionchanged:: 3.3
Martin Panterd21e0b52015-10-10 10:36:22 +0000486 Added ``yield from <expr>`` to delegate control flow to a subiterator.
Nick Coghlan0ed80192012-01-14 14:43:24 +1000487
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500488The parentheses may be omitted when the yield expression is the sole expression
489on the right hand side of an assignment statement.
490
491.. seealso::
492
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300493 :pep:`255` - Simple Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500494 The proposal for adding generators and the :keyword:`yield` statement to Python.
495
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300496 :pep:`342` - Coroutines via Enhanced Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500497 The proposal to enhance the API and syntax of generators, making them
498 usable as simple coroutines.
499
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300500 :pep:`380` - Syntax for Delegating to a Subgenerator
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500501 The proposal to introduce the :token:`yield_from` syntax, making delegation
502 to sub-generators easy.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000503
Georg Brandl116aa622007-08-15 14:28:22 +0000504.. index:: object: generator
Yury Selivanov66f88282015-06-24 11:04:15 -0400505.. _generator-methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000506
R David Murray2c1d1d62012-08-17 20:48:59 -0400507Generator-iterator methods
508^^^^^^^^^^^^^^^^^^^^^^^^^^
509
510This subsection describes the methods of a generator iterator. They can
511be used to control the execution of a generator function.
512
513Note that calling any of the generator methods below when the generator
514is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516.. index:: exception: StopIteration
517
518
Georg Brandl96593ed2007-09-07 14:15:41 +0000519.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000520
Georg Brandl96593ed2007-09-07 14:15:41 +0000521 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500522 executed yield expression. When a generator function is resumed with a
523 :meth:`~generator.__next__` method, the current yield expression always
524 evaluates to :const:`None`. The execution then continues to the next yield
525 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300526 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500527 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000528 exception is raised.
529
530 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
531 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000532
533
534.. method:: generator.send(value)
535
536 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500537 *value* argument becomes the result of the current yield expression. The
538 :meth:`send` method returns the next value yielded by the generator, or
539 raises :exc:`StopIteration` if the generator exits without yielding another
540 value. When :meth:`send` is called to start the generator, it must be called
541 with :const:`None` as the argument, because there is no yield expression that
542 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000543
544
545.. method:: generator.throw(type[, value[, traceback]])
546
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700547 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000548 and returns the next value yielded by the generator function. If the generator
549 exits without yielding another value, a :exc:`StopIteration` exception is
550 raised. If the generator function does not catch the passed-in exception, or
551 raises a different exception, then that exception propagates to the caller.
552
553.. index:: exception: GeneratorExit
554
555
556.. method:: generator.close()
557
558 Raises a :exc:`GeneratorExit` at the point where the generator function was
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400559 paused. If the generator function then exits gracefully, is already closed,
560 or raises :exc:`GeneratorExit` (by not catching the exception), close
561 returns to its caller. If the generator yields a value, a
562 :exc:`RuntimeError` is raised. If the generator raises any other exception,
563 it is propagated to the caller. :meth:`close` does nothing if the generator
564 has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000565
Chris Jerdonek2654b862012-12-23 15:31:57 -0800566.. index:: single: yield; examples
567
568Examples
569^^^^^^^^
570
Georg Brandl116aa622007-08-15 14:28:22 +0000571Here is a simple example that demonstrates the behavior of generators and
572generator functions::
573
574 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000575 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000576 ... try:
577 ... while True:
578 ... try:
579 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000580 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000581 ... value = e
582 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000583 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000584 ...
585 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000586 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000587 Execution starts when 'next()' is called for the first time.
588 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000589 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000590 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000591 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000592 2
593 >>> generator.throw(TypeError, "spam")
594 TypeError('spam',)
595 >>> generator.close()
596 Don't forget to clean up when 'close()' is called.
597
Chris Jerdonek2654b862012-12-23 15:31:57 -0800598For examples using ``yield from``, see :ref:`pep-380` in "What's New in
599Python."
600
Yury Selivanov03660042016-12-15 17:36:05 -0500601.. _asynchronous-generator-functions:
602
603Asynchronous generator functions
604^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
605
606The presence of a yield expression in a function or method defined using
607:keyword:`async def` further defines the function as a
608:term:`asynchronous generator` function.
609
610When an asynchronous generator function is called, it returns an
611asynchronous iterator known as an asynchronous generator object.
612That object then controls the execution of the generator function.
613An asynchronous generator object is typically used in an
614:keyword:`async for` statement in a coroutine function analogously to
615how a generator object would be used in a :keyword:`for` statement.
616
617Calling one of the asynchronous generator's methods returns an
618:term:`awaitable` object, and the execution starts when this object
619is awaited on. At that time, the execution proceeds to the first yield
620expression, where it is suspended again, returning the value of
621:token:`expression_list` to the awaiting coroutine. As with a generator,
622suspension means that all local state is retained, including the
623current bindings of local variables, the instruction pointer, the internal
624evaluation stack, and the state of any exception handling. When the execution
625is resumed by awaiting on the next object returned by the asynchronous
626generator's methods, the function can proceed exactly as if the yield
627expression were just another external call. The value of the yield expression
628after resuming depends on the method which resumed the execution. If
629:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
630:meth:`~agen.asend` is used, then the result will be the value passed in to
631that method.
632
633In an asynchronous generator function, yield expressions are allowed anywhere
634in a :keyword:`try` construct. However, if an asynchronous generator is not
635resumed before it is finalized (by reaching a zero reference count or by
636being garbage collected), then a yield expression within a :keyword:`try`
637construct could result in a failure to execute pending :keyword:`finally`
638clauses. In this case, it is the responsibility of the event loop or
639scheduler running the asynchronous generator to call the asynchronous
640generator-iterator's :meth:`~agen.aclose` method and run the resulting
641coroutine object, thus allowing any pending :keyword:`finally` clauses
642to execute.
643
644To take care of finalization, an event loop should define
645a *finalizer* function which takes an asynchronous generator-iterator
646and presumably calls :meth:`~agen.aclose` and executes the coroutine.
647This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`.
648When first iterated over, an asynchronous generator-iterator will store the
649registered *finalizer* to be called upon finalization. For a reference example
650of a *finalizer* method see the implementation of
651``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`.
652
653The expression ``yield from <expr>`` is a syntax error when used in an
654asynchronous generator function.
655
656.. index:: object: asynchronous-generator
657.. _asynchronous-generator-methods:
658
659Asynchronous generator-iterator methods
660^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
661
662This subsection describes the methods of an asynchronous generator iterator,
663which are used to control the execution of a generator function.
664
665
666.. index:: exception: StopAsyncIteration
667
668.. coroutinemethod:: agen.__anext__()
669
670 Returns an awaitable which when run starts to execute the asynchronous
671 generator or resumes it at the last executed yield expression. When an
672 asynchronous generator function is resumed with a :meth:`~agen.__anext__`
673 method, the current yield expression always evaluates to :const:`None` in
674 the returned awaitable, which when run will continue to the next yield
675 expression. The value of the :token:`expression_list` of the yield
676 expression is the value of the :exc:`StopIteration` exception raised by
677 the completing coroutine. If the asynchronous generator exits without
678 yielding another value, the awaitable instead raises an
679 :exc:`StopAsyncIteration` exception, signalling that the asynchronous
680 iteration has completed.
681
682 This method is normally called implicitly by a :keyword:`async for` loop.
683
684
685.. coroutinemethod:: agen.asend(value)
686
687 Returns an awaitable which when run resumes the execution of the
688 asynchronous generator. As with the :meth:`~generator.send()` method for a
689 generator, this "sends" a value into the asynchronous generator function,
690 and the *value* argument becomes the result of the current yield expression.
691 The awaitable returned by the :meth:`asend` method will return the next
692 value yielded by the generator as the value of the raised
693 :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the
694 asynchronous generator exits without yielding another value. When
695 :meth:`asend` is called to start the asynchronous
696 generator, it must be called with :const:`None` as the argument,
697 because there is no yield expression that could receive the value.
698
699
700.. coroutinemethod:: agen.athrow(type[, value[, traceback]])
701
702 Returns an awaitable that raises an exception of type ``type`` at the point
703 where the asynchronous generator was paused, and returns the next value
704 yielded by the generator function as the value of the raised
705 :exc:`StopIteration` exception. If the asynchronous generator exits
706 without yielding another value, an :exc:`StopAsyncIteration` exception is
707 raised by the awaitable.
708 If the generator function does not catch the passed-in exception, or
delirious-lettuce3378b202017-05-19 14:37:57 -0600709 raises a different exception, then when the awaitable is run that exception
Yury Selivanov03660042016-12-15 17:36:05 -0500710 propagates to the caller of the awaitable.
711
712.. index:: exception: GeneratorExit
713
714
715.. coroutinemethod:: agen.aclose()
716
717 Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
718 the asynchronous generator function at the point where it was paused.
719 If the asynchronous generator function then exits gracefully, is already
720 closed, or raises :exc:`GeneratorExit` (by not catching the exception),
721 then the returned awaitable will raise a :exc:`StopIteration` exception.
722 Any further awaitables returned by subsequent calls to the asynchronous
723 generator will raise a :exc:`StopAsyncIteration` exception. If the
724 asynchronous generator yields a value, a :exc:`RuntimeError` is raised
725 by the awaitable. If the asynchronous generator raises any other exception,
726 it is propagated to the caller of the awaitable. If the asynchronous
727 generator has already exited due to an exception or normal exit, then
728 further calls to :meth:`aclose` will return an awaitable that does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Georg Brandl116aa622007-08-15 14:28:22 +0000730.. _primaries:
731
732Primaries
733=========
734
735.. index:: single: primary
736
737Primaries represent the most tightly bound operations of the language. Their
738syntax is:
739
740.. productionlist::
741 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
742
743
744.. _attribute-references:
745
746Attribute references
747--------------------
748
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300749.. index::
750 pair: attribute; reference
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200751 single: . (dot); attribute reference
Georg Brandl116aa622007-08-15 14:28:22 +0000752
753An attribute reference is a primary followed by a period and a name:
754
755.. productionlist::
756 attributeref: `primary` "." `identifier`
757
758.. index::
759 exception: AttributeError
760 object: module
761 object: list
762
763The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000764references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700765attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500766overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700767the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
768the object produced is determined by the object. Multiple evaluations of the
769same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000770
771
772.. _subscriptions:
773
774Subscriptions
775-------------
776
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300777.. index::
778 single: subscription
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200779 single: [] (square brackets); subscription
Georg Brandl116aa622007-08-15 14:28:22 +0000780
781.. index::
782 object: sequence
783 object: mapping
784 object: string
785 object: tuple
786 object: list
787 object: dictionary
788 pair: sequence; item
789
790A subscription selects an item of a sequence (string, tuple or list) or mapping
791(dictionary) object:
792
793.. productionlist::
794 subscription: `primary` "[" `expression_list` "]"
795
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700796The primary must evaluate to an object that supports subscription (lists or
797dictionaries for example). User-defined objects can support subscription by
798defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000799
800For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000801
802If the primary is a mapping, the expression list must evaluate to an object
803whose value is one of the keys of the mapping, and the subscription selects the
804value in the mapping that corresponds to that key. (The expression list is a
805tuple except if it has exactly one item.)
806
Andrés Delfino4fddd4e2018-06-15 15:24:25 -0300807If the primary is a sequence, the expression list must evaluate to an integer
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000808or a slice (as discussed in the following section).
809
810The formal syntax makes no special provision for negative indices in
811sequences; however, built-in sequences all provide a :meth:`__getitem__`
812method that interprets negative indices by adding the length of the sequence
813to the index (so that ``x[-1]`` selects the last item of ``x``). The
814resulting value must be a nonnegative integer less than the number of items in
815the sequence, and the subscription selects the item whose index is that value
816(counting from zero). Since the support for negative indices and slicing
817occurs in the object's :meth:`__getitem__` method, subclasses overriding
818this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000819
820.. index::
821 single: character
822 pair: string; item
823
824A string's items are characters. A character is not a separate data type but a
825string of exactly one character.
826
827
828.. _slicings:
829
830Slicings
831--------
832
833.. index::
834 single: slicing
835 single: slice
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200836 single: : (colon); slicing
837 single: , (comma); slicing
Georg Brandl116aa622007-08-15 14:28:22 +0000838
839.. index::
840 object: sequence
841 object: string
842 object: tuple
843 object: list
844
845A slicing selects a range of items in a sequence object (e.g., a string, tuple
846or list). Slicings may be used as expressions or as targets in assignment or
847:keyword:`del` statements. The syntax for a slicing:
848
849.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000850 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000851 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000852 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000853 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000854 lower_bound: `expression`
855 upper_bound: `expression`
856 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000857
858There is ambiguity in the formal syntax here: anything that looks like an
859expression list also looks like a slice list, so any subscription can be
860interpreted as a slicing. Rather than further complicating the syntax, this is
861disambiguated by defining that in this case the interpretation as a subscription
862takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000863slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000864
865.. index::
866 single: start (slice object attribute)
867 single: stop (slice object attribute)
868 single: step (slice object attribute)
869
Georg Brandla4c8c472014-10-31 10:38:49 +0100870The semantics for a slicing are as follows. The primary is indexed (using the
871same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000872normal subscription) with a key that is constructed from the slice list, as
873follows. If the slice list contains at least one comma, the key is a tuple
874containing the conversion of the slice items; otherwise, the conversion of the
875lone slice item is the key. The conversion of a slice item that is an
876expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300877object (see section :ref:`types`) whose :attr:`~slice.start`,
878:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
879expressions given as lower bound, upper bound and stride, respectively,
880substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000881
882
Chris Jerdonekb4309942012-12-25 14:54:44 -0800883.. index::
884 object: callable
885 single: call
886 single: argument; call semantics
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200887 single: () (parentheses); call
888 single: , (comma); argument list
889 single: = (equals); in function calls
Chris Jerdonekb4309942012-12-25 14:54:44 -0800890
Georg Brandl116aa622007-08-15 14:28:22 +0000891.. _calls:
892
893Calls
894-----
895
Chris Jerdonekb4309942012-12-25 14:54:44 -0800896A call calls a callable object (e.g., a :term:`function`) with a possibly empty
897series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000898
899.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000900 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Martin Panter0c0da482016-06-12 01:46:50 +0000901 argument_list: `positional_arguments` ["," `starred_and_keywords`]
902 : ["," `keywords_arguments`]
903 : | `starred_and_keywords` ["," `keywords_arguments`]
904 : | `keywords_arguments`
905 positional_arguments: ["*"] `expression` ("," ["*"] `expression`)*
906 starred_and_keywords: ("*" `expression` | `keyword_item`)
907 : ("," "*" `expression` | "," `keyword_item`)*
908 keywords_arguments: (`keyword_item` | "**" `expression`)
Martin Panter7106a512016-12-24 10:20:38 +0000909 : ("," `keyword_item` | "," "**" `expression`)*
Georg Brandl116aa622007-08-15 14:28:22 +0000910 keyword_item: `identifier` "=" `expression`
911
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700912An optional trailing comma may be present after the positional and keyword arguments
913but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000914
Chris Jerdonekb4309942012-12-25 14:54:44 -0800915.. index::
916 single: parameter; call semantics
917
Georg Brandl116aa622007-08-15 14:28:22 +0000918The primary must evaluate to a callable object (user-defined functions, built-in
919functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000920instances, and all objects having a :meth:`__call__` method are callable). All
921argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800922to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000923
924.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000925
926If keyword arguments are present, they are first converted to positional
927arguments, as follows. First, a list of unfilled slots is created for the
928formal parameters. If there are N positional arguments, they are placed in the
929first N slots. Next, for each keyword argument, the identifier is used to
930determine the corresponding slot (if the identifier is the same as the first
931formal parameter name, the first slot is used, and so on). If the slot is
932already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
933the argument is placed in the slot, filling it (even if the expression is
934``None``, it fills the slot). When all arguments have been processed, the slots
935that are still unfilled are filled with the corresponding default value from the
936function definition. (Default values are calculated, once, when the function is
937defined; thus, a mutable object such as a list or dictionary used as default
938value will be shared by all calls that don't specify an argument value for the
939corresponding slot; this should usually be avoided.) If there are any unfilled
940slots for which no default value is specified, a :exc:`TypeError` exception is
941raised. Otherwise, the list of filled slots is used as the argument list for
942the call.
943
Georg Brandl495f7b52009-10-27 15:28:25 +0000944.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000945
Georg Brandl495f7b52009-10-27 15:28:25 +0000946 An implementation may provide built-in functions whose positional parameters
947 do not have names, even if they are 'named' for the purpose of documentation,
948 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000949 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000950 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000951
Georg Brandl116aa622007-08-15 14:28:22 +0000952If there are more positional arguments than there are formal parameter slots, a
953:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
954``*identifier`` is present; in this case, that formal parameter receives a tuple
955containing the excess positional arguments (or an empty tuple if there were no
956excess positional arguments).
957
958If any keyword argument does not correspond to a formal parameter name, a
959:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
960``**identifier`` is present; in this case, that formal parameter receives a
961dictionary containing the excess keyword arguments (using the keywords as keys
962and the argument values as corresponding values), or a (new) empty dictionary if
963there were no excess keyword arguments.
964
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300965.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200966 single: * (asterisk); in function calls
Martin Panter0c0da482016-06-12 01:46:50 +0000967 single: unpacking; in function calls
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300968
Georg Brandl116aa622007-08-15 14:28:22 +0000969If the syntax ``*expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +0000970evaluate to an :term:`iterable`. Elements from these iterables are
971treated as if they were additional positional arguments. For the call
972``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*,
973this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
974*y1*, ..., *yM*, *x3*, *x4*.
Georg Brandl116aa622007-08-15 14:28:22 +0000975
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000976A consequence of this is that although the ``*expression`` syntax may appear
Martin Panter0c0da482016-06-12 01:46:50 +0000977*after* explicit keyword arguments, it is processed *before* the
978keyword arguments (and any ``**expression`` arguments -- see below). So::
Georg Brandl116aa622007-08-15 14:28:22 +0000979
980 >>> def f(a, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300981 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000982 ...
983 >>> f(b=1, *(2,))
984 2 1
985 >>> f(a=1, *(2,))
986 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530987 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000988 TypeError: f() got multiple values for keyword argument 'a'
989 >>> f(1, *(2,))
990 1 2
991
992It is unusual for both keyword arguments and the ``*expression`` syntax to be
993used in the same call, so in practice this confusion does not arise.
994
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300995.. index::
996 single: **; in function calls
997
Georg Brandl116aa622007-08-15 14:28:22 +0000998If the syntax ``**expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +0000999evaluate to a :term:`mapping`, the contents of which are treated as
1000additional keyword arguments. If a keyword is already present
1001(as an explicit keyword argument, or from another unpacking),
1002a :exc:`TypeError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001003
1004Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
1005used as positional argument slots or as keyword argument names.
1006
Martin Panter0c0da482016-06-12 01:46:50 +00001007.. versionchanged:: 3.5
1008 Function calls accept any number of ``*`` and ``**`` unpackings,
1009 positional arguments may follow iterable unpackings (``*``),
1010 and keyword arguments may follow dictionary unpackings (``**``).
1011 Originally proposed by :pep:`448`.
1012
Georg Brandl116aa622007-08-15 14:28:22 +00001013A call always returns some value, possibly ``None``, unless it raises an
1014exception. How this value is computed depends on the type of the callable
1015object.
1016
1017If it is---
1018
1019a user-defined function:
1020 .. index::
1021 pair: function; call
1022 triple: user-defined; function; call
1023 object: user-defined function
1024 object: function
1025
1026 The code block for the function is executed, passing it the argument list. The
1027 first thing the code block will do is bind the formal parameters to the
1028 arguments; this is described in section :ref:`function`. When the code block
1029 executes a :keyword:`return` statement, this specifies the return value of the
1030 function call.
1031
1032a built-in function or method:
1033 .. index::
1034 pair: function; call
1035 pair: built-in function; call
1036 pair: method; call
1037 pair: built-in method; call
1038 object: built-in method
1039 object: built-in function
1040 object: method
1041 object: function
1042
1043 The result is up to the interpreter; see :ref:`built-in-funcs` for the
1044 descriptions of built-in functions and methods.
1045
1046a class object:
1047 .. index::
1048 object: class
1049 pair: class object; call
1050
1051 A new instance of that class is returned.
1052
1053a class instance method:
1054 .. index::
1055 object: class instance
1056 object: instance
1057 pair: class instance; call
1058
1059 The corresponding user-defined function is called, with an argument list that is
1060 one longer than the argument list of the call: the instance becomes the first
1061 argument.
1062
1063a class instance:
1064 .. index::
1065 pair: instance; call
1066 single: __call__() (object method)
1067
1068 The class must define a :meth:`__call__` method; the effect is then the same as
1069 if that method was called.
1070
1071
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001072.. index:: keyword: await
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001073.. _await:
1074
1075Await expression
1076================
1077
1078Suspend the execution of :term:`coroutine` on an :term:`awaitable` object.
1079Can only be used inside a :term:`coroutine function`.
1080
1081.. productionlist::
Serhiy Storchakac7cc9852016-05-08 21:59:46 +03001082 await_expr: "await" `primary`
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001083
1084.. versionadded:: 3.5
1085
1086
Georg Brandl116aa622007-08-15 14:28:22 +00001087.. _power:
1088
1089The power operator
1090==================
1091
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001092.. index::
1093 pair: power; operation
1094 operator: **
1095
Georg Brandl116aa622007-08-15 14:28:22 +00001096The power operator binds more tightly than unary operators on its left; it binds
1097less tightly than unary operators on its right. The syntax is:
1098
1099.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001100 power: (`await_expr` | `primary`) ["**" `u_expr`]
Georg Brandl116aa622007-08-15 14:28:22 +00001101
1102Thus, in an unparenthesized sequence of power and unary operators, the operators
1103are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +00001104for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001105
1106The power operator has the same semantics as the built-in :func:`pow` function,
1107when called with two arguments: it yields its left argument raised to the power
1108of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +00001109type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +00001110
Georg Brandl96593ed2007-09-07 14:15:41 +00001111For int operands, the result has the same type as the operands unless the second
1112argument is negative; in that case, all arguments are converted to float and a
1113float result is delivered. For example, ``10**2`` returns ``100``, but
1114``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +00001115
1116Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +00001117Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001118number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001119
1120
1121.. _unary:
1122
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001123Unary arithmetic and bitwise operations
1124=======================================
Georg Brandl116aa622007-08-15 14:28:22 +00001125
1126.. index::
1127 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +00001128 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001129
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001130All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +00001131
1132.. productionlist::
1133 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
1134
1135.. index::
1136 single: negation
1137 single: minus
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001138 single: operator; - (minus)
1139 single: - (minus); unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001140
1141The unary ``-`` (minus) operator yields the negation of its numeric argument.
1142
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001143.. index::
1144 single: plus
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001145 single: operator; + (plus)
1146 single: + (plus); unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001147
1148The unary ``+`` (plus) operator yields its numeric argument unchanged.
1149
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001150.. index::
1151 single: inversion
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001152 operator: ~ (tilde)
Christian Heimesfaf2f632008-01-06 16:59:19 +00001153
Georg Brandl95817b32008-05-11 14:30:18 +00001154The unary ``~`` (invert) operator yields the bitwise inversion of its integer
1155argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
1156applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00001157
1158.. index:: exception: TypeError
1159
1160In all three cases, if the argument does not have the proper type, a
1161:exc:`TypeError` exception is raised.
1162
1163
1164.. _binary:
1165
1166Binary arithmetic operations
1167============================
1168
1169.. index:: triple: binary; arithmetic; operation
1170
1171The binary arithmetic operations have the conventional priority levels. Note
1172that some of these operations also apply to certain non-numeric types. Apart
1173from the power operator, there are only two levels, one for multiplicative
1174operators and one for additive operators:
1175
1176.. productionlist::
Benjamin Petersond51374e2014-04-09 23:55:56 -04001177 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
Andrés Delfinocaccca782018-07-07 17:24:46 -03001178 : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` |
Benjamin Petersond51374e2014-04-09 23:55:56 -04001179 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001180 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
1181
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001182.. index::
1183 single: multiplication
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001184 operator: * (asterisk)
Georg Brandl116aa622007-08-15 14:28:22 +00001185
1186The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +00001187arguments must either both be numbers, or one argument must be an integer and
1188the other must be a sequence. In the former case, the numbers are converted to a
1189common type and then multiplied together. In the latter case, sequence
1190repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001191
Andrés Delfino69511862018-06-15 16:23:00 -03001192.. index::
1193 single: matrix multiplication
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001194 operator: @ (at)
Benjamin Petersond51374e2014-04-09 23:55:56 -04001195
1196The ``@`` (at) operator is intended to be used for matrix multiplication. No
1197builtin Python types implement this operator.
1198
1199.. versionadded:: 3.5
1200
Georg Brandl116aa622007-08-15 14:28:22 +00001201.. index::
1202 exception: ZeroDivisionError
1203 single: division
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001204 operator: / (slash)
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001205 operator: //
Georg Brandl116aa622007-08-15 14:28:22 +00001206
1207The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
1208their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +02001209Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +00001210integer; the result is that of mathematical division with the 'floor' function
1211applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
1212exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001213
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001214.. index::
1215 single: modulo
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001216 operator: % (percent)
Georg Brandl116aa622007-08-15 14:28:22 +00001217
1218The ``%`` (modulo) operator yields the remainder from the division of the first
1219argument by the second. The numeric arguments are first converted to a common
1220type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
1221arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
1222(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
1223result with the same sign as its second operand (or zero); the absolute value of
1224the result is strictly smaller than the absolute value of the second operand
1225[#]_.
1226
Georg Brandl96593ed2007-09-07 14:15:41 +00001227The floor division and modulo operators are connected by the following
1228identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
1229connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
1230x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +00001231
1232In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +00001233also overloaded by string objects to perform old-style string formatting (also
1234known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +00001235Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +00001236
1237The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +00001238function are not defined for complex numbers. Instead, convert to a floating
1239point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +00001240
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001241.. index::
1242 single: addition
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001243 single: operator; + (plus)
1244 single: + (plus); binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001245
Georg Brandl96593ed2007-09-07 14:15:41 +00001246The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001247must either both be numbers or both be sequences of the same type. In the
1248former case, the numbers are converted to a common type and then added together.
1249In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +00001250
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001251.. index::
1252 single: subtraction
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001253 single: operator; - (minus)
1254 single: - (minus); binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001255
1256The ``-`` (subtraction) operator yields the difference of its arguments. The
1257numeric arguments are first converted to a common type.
1258
1259
1260.. _shifting:
1261
1262Shifting operations
1263===================
1264
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001265.. index::
1266 pair: shifting; operation
1267 operator: <<
1268 operator: >>
Georg Brandl116aa622007-08-15 14:28:22 +00001269
1270The shifting operations have lower priority than the arithmetic operations:
1271
1272.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001273 shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001274
Georg Brandl96593ed2007-09-07 14:15:41 +00001275These operators accept integers as arguments. They shift the first argument to
1276the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001277
1278.. index:: exception: ValueError
1279
Georg Brandl0aaae262013-10-08 21:47:18 +02001280A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
1281shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001282
1283
1284.. _bitwise:
1285
Christian Heimesfaf2f632008-01-06 16:59:19 +00001286Binary bitwise operations
1287=========================
Georg Brandl116aa622007-08-15 14:28:22 +00001288
Christian Heimesfaf2f632008-01-06 16:59:19 +00001289.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001290
1291Each of the three bitwise operations has a different priority level:
1292
1293.. productionlist::
1294 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1295 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1296 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1297
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001298.. index::
1299 pair: bitwise; and
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001300 operator: & (ampersand)
Georg Brandl116aa622007-08-15 14:28:22 +00001301
Georg Brandl96593ed2007-09-07 14:15:41 +00001302The ``&`` operator yields the bitwise AND of its arguments, which must be
1303integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001304
1305.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001306 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001307 pair: exclusive; or
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001308 operator: ^ (caret)
Georg Brandl116aa622007-08-15 14:28:22 +00001309
1310The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001311must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001312
1313.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001314 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001315 pair: inclusive; or
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001316 operator: | (vertical bar)
Georg Brandl116aa622007-08-15 14:28:22 +00001317
1318The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001319must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001320
1321
1322.. _comparisons:
1323
1324Comparisons
1325===========
1326
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001327.. index::
1328 single: comparison
1329 pair: C; language
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001330 operator: < (less)
1331 operator: > (greater)
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001332 operator: <=
1333 operator: >=
1334 operator: ==
1335 operator: !=
Georg Brandl116aa622007-08-15 14:28:22 +00001336
1337Unlike C, all comparison operations in Python have the same priority, which is
1338lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1339C, expressions like ``a < b < c`` have the interpretation that is conventional
1340in mathematics:
1341
1342.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001343 comparison: `or_expr` (`comp_operator` `or_expr`)*
Georg Brandl116aa622007-08-15 14:28:22 +00001344 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1345 : | "is" ["not"] | ["not"] "in"
1346
1347Comparisons yield boolean values: ``True`` or ``False``.
1348
1349.. index:: pair: chaining; comparisons
1350
1351Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1352``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1353cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1354
Guido van Rossum04110fb2007-08-24 16:32:05 +00001355Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1356*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1357to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1358evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001359
Guido van Rossum04110fb2007-08-24 16:32:05 +00001360Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001361*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1362pretty).
1363
Martin Panteraa0da862015-09-23 05:28:13 +00001364Value comparisons
1365-----------------
1366
Georg Brandl116aa622007-08-15 14:28:22 +00001367The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
Martin Panteraa0da862015-09-23 05:28:13 +00001368values of two objects. The objects do not need to have the same type.
Georg Brandl116aa622007-08-15 14:28:22 +00001369
Martin Panteraa0da862015-09-23 05:28:13 +00001370Chapter :ref:`objects` states that objects have a value (in addition to type
1371and identity). The value of an object is a rather abstract notion in Python:
1372For example, there is no canonical access method for an object's value. Also,
1373there is no requirement that the value of an object should be constructed in a
1374particular way, e.g. comprised of all its data attributes. Comparison operators
1375implement a particular notion of what the value of an object is. One can think
1376of them as defining the value of an object indirectly, by means of their
1377comparison implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00001378
Martin Panteraa0da862015-09-23 05:28:13 +00001379Because all types are (direct or indirect) subtypes of :class:`object`, they
1380inherit the default comparison behavior from :class:`object`. Types can
1381customize their comparison behavior by implementing
1382:dfn:`rich comparison methods` like :meth:`__lt__`, described in
1383:ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001384
Martin Panteraa0da862015-09-23 05:28:13 +00001385The default behavior for equality comparison (``==`` and ``!=``) is based on
1386the identity of the objects. Hence, equality comparison of instances with the
1387same identity results in equality, and equality comparison of instances with
1388different identities results in inequality. A motivation for this default
1389behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1390implies ``x == y``).
1391
1392A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1393an attempt raises :exc:`TypeError`. A motivation for this default behavior is
1394the lack of a similar invariant as for equality.
1395
1396The behavior of the default equality comparison, that instances with different
1397identities are always unequal, may be in contrast to what types will need that
1398have a sensible definition of object value and value-based equality. Such
1399types will need to customize their comparison behavior, and in fact, a number
1400of built-in types have done that.
1401
1402The following list describes the comparison behavior of the most important
1403built-in types.
1404
1405* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1406 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
1407 compared within and across their types, with the restriction that complex
1408 numbers do not support order comparison. Within the limits of the types
1409 involved, they compare mathematically (algorithmically) correct without loss
1410 of precision.
1411
Tony Fluryad8a0002018-09-14 18:48:50 +01001412 The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are
1413 special. Any ordered comparison of a number to a not-a-number value is false.
1414 A counter-intuitive implication is that not-a-number values are not equal to
1415 themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3``, ``x
1416 == x``, ``x != x`` are all false. This behavior is compliant with IEEE 754.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001417
Martin Panteraa0da862015-09-23 05:28:13 +00001418* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
1419 compared within and across their types. They compare lexicographically using
1420 the numeric values of their elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001421
Martin Panteraa0da862015-09-23 05:28:13 +00001422* Strings (instances of :class:`str`) compare lexicographically using the
1423 numerical Unicode code points (the result of the built-in function
1424 :func:`ord`) of their characters. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001425
Martin Panteraa0da862015-09-23 05:28:13 +00001426 Strings and binary sequences cannot be directly compared.
Georg Brandl116aa622007-08-15 14:28:22 +00001427
Martin Panteraa0da862015-09-23 05:28:13 +00001428* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can
1429 be compared only within each of their types, with the restriction that ranges
1430 do not support order comparison. Equality comparison across these types
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +02001431 results in inequality, and ordering comparison across these types raises
Martin Panteraa0da862015-09-23 05:28:13 +00001432 :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001433
Martin Panteraa0da862015-09-23 05:28:13 +00001434 Sequences compare lexicographically using comparison of corresponding
1435 elements, whereby reflexivity of the elements is enforced.
Georg Brandl116aa622007-08-15 14:28:22 +00001436
Martin Panteraa0da862015-09-23 05:28:13 +00001437 In enforcing reflexivity of elements, the comparison of collections assumes
1438 that for a collection element ``x``, ``x == x`` is always true. Based on
1439 that assumption, element identity is compared first, and element comparison
1440 is performed only for distinct elements. This approach yields the same
1441 result as a strict element comparison would, if the compared elements are
1442 reflexive. For non-reflexive elements, the result is different than for
1443 strict element comparison, and may be surprising: The non-reflexive
1444 not-a-number values for example result in the following comparison behavior
1445 when used in a list::
1446
1447 >>> nan = float('NaN')
1448 >>> nan is nan
1449 True
1450 >>> nan == nan
1451 False <-- the defined non-reflexive behavior of NaN
1452 >>> [nan] == [nan]
1453 True <-- list enforces reflexivity and tests identity first
1454
1455 Lexicographical comparison between built-in collections works as follows:
1456
1457 - For two collections to compare equal, they must be of the same type, have
1458 the same length, and each pair of corresponding elements must compare
1459 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1460 same).
1461
1462 - Collections that support order comparison are ordered the same as their
1463 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same
1464 value as ``x <= y``). If a corresponding element does not exist, the
1465 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1466 true).
1467
1468* Mappings (instances of :class:`dict`) compare equal if and only if they have
cocoatomocdcac032017-03-31 14:48:49 +09001469 equal `(key, value)` pairs. Equality comparison of the keys and values
Martin Panteraa0da862015-09-23 05:28:13 +00001470 enforces reflexivity.
1471
1472 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
1473
1474* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within
1475 and across their types.
1476
1477 They define order
1478 comparison operators to mean subset and superset tests. Those relations do
1479 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}``
1480 are not equal, nor subsets of one another, nor supersets of one
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001481 another). Accordingly, sets are not appropriate arguments for functions
Martin Panteraa0da862015-09-23 05:28:13 +00001482 which depend on total ordering (for example, :func:`min`, :func:`max`, and
1483 :func:`sorted` produce undefined results given a list of sets as inputs).
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001484
Martin Panteraa0da862015-09-23 05:28:13 +00001485 Comparison of sets enforces reflexivity of its elements.
Georg Brandl116aa622007-08-15 14:28:22 +00001486
Martin Panteraa0da862015-09-23 05:28:13 +00001487* Most other built-in types have no comparison methods implemented, so they
1488 inherit the default comparison behavior.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001489
Martin Panteraa0da862015-09-23 05:28:13 +00001490User-defined classes that customize their comparison behavior should follow
1491some consistency rules, if possible:
1492
1493* Equality comparison should be reflexive.
1494 In other words, identical objects should compare equal:
1495
1496 ``x is y`` implies ``x == y``
1497
1498* Comparison should be symmetric.
1499 In other words, the following expressions should have the same result:
1500
1501 ``x == y`` and ``y == x``
1502
1503 ``x != y`` and ``y != x``
1504
1505 ``x < y`` and ``y > x``
1506
1507 ``x <= y`` and ``y >= x``
1508
1509* Comparison should be transitive.
1510 The following (non-exhaustive) examples illustrate that:
1511
1512 ``x > y and y > z`` implies ``x > z``
1513
1514 ``x < y and y <= z`` implies ``x < z``
1515
1516* Inverse comparison should result in the boolean negation.
1517 In other words, the following expressions should have the same result:
1518
1519 ``x == y`` and ``not x != y``
1520
1521 ``x < y`` and ``not x >= y`` (for total ordering)
1522
1523 ``x > y`` and ``not x <= y`` (for total ordering)
1524
1525 The last two expressions apply to totally ordered collections (e.g. to
1526 sequences, but not to sets or mappings). See also the
1527 :func:`~functools.total_ordering` decorator.
1528
Martin Panter8dbb0ca2017-01-29 10:00:23 +00001529* The :func:`hash` result should be consistent with equality.
1530 Objects that are equal should either have the same hash value,
1531 or be marked as unhashable.
1532
Martin Panteraa0da862015-09-23 05:28:13 +00001533Python does not enforce these consistency rules. In fact, the not-a-number
1534values are an example for not following these rules.
1535
1536
1537.. _in:
1538.. _not in:
Georg Brandl495f7b52009-10-27 15:28:25 +00001539.. _membership-test-details:
1540
Martin Panteraa0da862015-09-23 05:28:13 +00001541Membership test operations
1542--------------------------
1543
Georg Brandl96593ed2007-09-07 14:15:41 +00001544The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301545s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
1546``x not in s`` returns the negation of ``x in s``. All built-in sequences and
1547set types support this as well as dictionary, for which :keyword:`in` tests
1548whether the dictionary has a given key. For container types such as list, tuple,
1549set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001550to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001551
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301552For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
Georg Brandl4b491312007-08-31 09:22:56 +00001553substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1554always considered to be a substring of any other string, so ``"" in "abc"`` will
1555return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001556
Georg Brandl116aa622007-08-15 14:28:22 +00001557For user-defined classes which define the :meth:`__contains__` method, ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301558y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and
1559``False`` otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001560
Georg Brandl495f7b52009-10-27 15:28:25 +00001561For user-defined classes which do not define :meth:`__contains__` but do define
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301562:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z`` with ``x == z`` is
Georg Brandl495f7b52009-10-27 15:28:25 +00001563produced while iterating over ``y``. If an exception is raised during the
1564iteration, it is as if :keyword:`in` raised that exception.
1565
1566Lastly, the old-style iteration protocol is tried: if a class defines
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301567:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
Georg Brandl116aa622007-08-15 14:28:22 +00001568integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001569raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001570if :keyword:`in` raised that exception).
1571
1572.. index::
1573 operator: in
1574 operator: not in
1575 pair: membership; test
1576 object: sequence
1577
1578The operator :keyword:`not in` is defined to have the inverse true value of
1579:keyword:`in`.
1580
1581.. index::
1582 operator: is
1583 operator: is not
1584 pair: identity; test
1585
Martin Panteraa0da862015-09-23 05:28:13 +00001586
1587.. _is:
1588.. _is not:
1589
1590Identity comparisons
1591--------------------
1592
Georg Brandl116aa622007-08-15 14:28:22 +00001593The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
Raymond Hettinger06e18a72016-09-11 17:23:49 -07001594is y`` is true if and only if *x* and *y* are the same object. Object identity
1595is determined using the :meth:`id` function. ``x is not y`` yields the inverse
1596truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001597
1598
1599.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001600.. _and:
1601.. _or:
1602.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001603
1604Boolean operations
1605==================
1606
1607.. index::
1608 pair: Conditional; expression
1609 pair: Boolean; operation
1610
Georg Brandl116aa622007-08-15 14:28:22 +00001611.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001612 or_test: `and_test` | `or_test` "or" `and_test`
1613 and_test: `not_test` | `and_test` "and" `not_test`
1614 not_test: `comparison` | "not" `not_test`
1615
1616In the context of Boolean operations, and also when expressions are used by
1617control flow statements, the following values are interpreted as false:
1618``False``, ``None``, numeric zero of all types, and empty strings and containers
1619(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001620other values are interpreted as true. User-defined objects can customize their
1621truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001622
1623.. index:: operator: not
1624
1625The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1626otherwise.
1627
Georg Brandl116aa622007-08-15 14:28:22 +00001628.. index:: operator: and
1629
1630The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1631returned; otherwise, *y* is evaluated and the resulting value is returned.
1632
1633.. index:: operator: or
1634
1635The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1636returned; otherwise, *y* is evaluated and the resulting value is returned.
1637
1638(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1639they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001640argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001641replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001642the desired value. Because :keyword:`not` has to create a new value, it
1643returns a boolean value regardless of the type of its argument
1644(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001645
1646
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001647Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001648=======================
1649
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001650.. index::
1651 pair: conditional; expression
1652 pair: ternary; operator
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001653 single: if; conditional expression
1654 single: else; conditional expression
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001655
1656.. productionlist::
1657 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001658 expression: `conditional_expression` | `lambda_expr`
1659 expression_nocond: `or_test` | `lambda_expr_nocond`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001660
1661Conditional expressions (sometimes called a "ternary operator") have the lowest
1662priority of all Python operations.
1663
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001664The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1665If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001666evaluated and its value is returned.
1667
1668See :pep:`308` for more details about conditional expressions.
1669
1670
Georg Brandl116aa622007-08-15 14:28:22 +00001671.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001672.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001673
1674Lambdas
1675=======
1676
1677.. index::
1678 pair: lambda; expression
1679 pair: lambda; form
1680 pair: anonymous; function
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001681 single: : (colon); lambda expression
Georg Brandl116aa622007-08-15 14:28:22 +00001682
1683.. productionlist::
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001684 lambda_expr: "lambda" [`parameter_list`] ":" `expression`
1685 lambda_expr_nocond: "lambda" [`parameter_list`] ":" `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001686
Zachary Ware2f78b842014-06-03 09:32:40 -05001687Lambda expressions (sometimes called lambda forms) are used to create anonymous
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001688functions. The expression ``lambda parameters: expression`` yields a function
Martin Panter1050d2d2016-07-26 11:18:21 +02001689object. The unnamed object behaves like a function object defined with:
1690
1691.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +00001692
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001693 def <lambda>(parameters):
Georg Brandl116aa622007-08-15 14:28:22 +00001694 return expression
1695
1696See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001697functions created with lambda expressions cannot contain statements or
1698annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001699
Georg Brandl116aa622007-08-15 14:28:22 +00001700
1701.. _exprlists:
1702
1703Expression lists
1704================
1705
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001706.. index::
1707 pair: expression; list
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001708 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +00001709
1710.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001711 expression_list: `expression` ("," `expression`)* [","]
1712 starred_list: `starred_item` ("," `starred_item`)* [","]
1713 starred_expression: `expression` | (`starred_item` ",")* [`starred_item`]
Martin Panter0c0da482016-06-12 01:46:50 +00001714 starred_item: `expression` | "*" `or_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001715
1716.. index:: object: tuple
1717
Martin Panter0c0da482016-06-12 01:46:50 +00001718Except when part of a list or set display, an expression list
1719containing at least one comma yields a tuple. The length of
Georg Brandl116aa622007-08-15 14:28:22 +00001720the tuple is the number of expressions in the list. The expressions are
1721evaluated from left to right.
1722
Martin Panter0c0da482016-06-12 01:46:50 +00001723.. index::
1724 pair: iterable; unpacking
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001725 single: * (asterisk); in expression lists
Martin Panter0c0da482016-06-12 01:46:50 +00001726
1727An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be
1728an :term:`iterable`. The iterable is expanded into a sequence of items,
1729which are included in the new tuple, list, or set, at the site of
1730the unpacking.
1731
1732.. versionadded:: 3.5
1733 Iterable unpacking in expression lists, originally proposed by :pep:`448`.
1734
Georg Brandl116aa622007-08-15 14:28:22 +00001735.. index:: pair: trailing; comma
1736
1737The trailing comma is required only to create a single tuple (a.k.a. a
1738*singleton*); it is optional in all other cases. A single expression without a
1739trailing comma doesn't create a tuple, but rather yields the value of that
1740expression. (To create an empty tuple, use an empty pair of parentheses:
1741``()``.)
1742
1743
1744.. _evalorder:
1745
1746Evaluation order
1747================
1748
1749.. index:: pair: evaluation; order
1750
Georg Brandl96593ed2007-09-07 14:15:41 +00001751Python evaluates expressions from left to right. Notice that while evaluating
1752an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001753
1754In the following lines, expressions will be evaluated in the arithmetic order of
1755their suffixes::
1756
1757 expr1, expr2, expr3, expr4
1758 (expr1, expr2, expr3, expr4)
1759 {expr1: expr2, expr3: expr4}
1760 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001761 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001762 expr3, expr4 = expr1, expr2
1763
1764
1765.. _operator-summary:
1766
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001767Operator precedence
1768===================
Georg Brandl116aa622007-08-15 14:28:22 +00001769
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001770.. index::
1771 pair: operator; precedence
Georg Brandl116aa622007-08-15 14:28:22 +00001772
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001773The following table summarizes the operator precedence in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001774precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001775the same box have the same precedence. Unless the syntax is explicitly given,
1776operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001777exponentiation, which groups from right to left).
1778
1779Note that comparisons, membership tests, and identity tests, all have the same
1780precedence and have a left-to-right chaining feature as described in the
1781:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001782
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001783
1784+-----------------------------------------------+-------------------------------------+
1785| Operator | Description |
1786+===============================================+=====================================+
1787| :keyword:`lambda` | Lambda expression |
1788+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001789| :keyword:`if` -- :keyword:`else` | Conditional expression |
1790+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001791| :keyword:`or` | Boolean OR |
1792+-----------------------------------------------+-------------------------------------+
1793| :keyword:`and` | Boolean AND |
1794+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001795| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001796+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001797| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001798| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001799| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001800+-----------------------------------------------+-------------------------------------+
1801| ``|`` | Bitwise OR |
1802+-----------------------------------------------+-------------------------------------+
1803| ``^`` | Bitwise XOR |
1804+-----------------------------------------------+-------------------------------------+
1805| ``&`` | Bitwise AND |
1806+-----------------------------------------------+-------------------------------------+
1807| ``<<``, ``>>`` | Shifts |
1808+-----------------------------------------------+-------------------------------------+
1809| ``+``, ``-`` | Addition and subtraction |
1810+-----------------------------------------------+-------------------------------------+
Benjamin Petersond51374e2014-04-09 23:55:56 -04001811| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
svelankar9b47af62017-09-17 20:56:16 -04001812| | multiplication, division, floor |
1813| | division, remainder [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001814+-----------------------------------------------+-------------------------------------+
1815| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1816+-----------------------------------------------+-------------------------------------+
1817| ``**`` | Exponentiation [#]_ |
1818+-----------------------------------------------+-------------------------------------+
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001819| :keyword:`await` ``x`` | Await expression |
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001820+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001821| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1822| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1823+-----------------------------------------------+-------------------------------------+
1824| ``(expressions...)``, | Binding or tuple display, |
1825| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001826| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001827| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001828+-----------------------------------------------+-------------------------------------+
1829
Georg Brandl116aa622007-08-15 14:28:22 +00001830
1831.. rubric:: Footnotes
1832
Georg Brandl116aa622007-08-15 14:28:22 +00001833.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1834 true numerically due to roundoff. For example, and assuming a platform on which
1835 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1836 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001837 1e100``, which is numerically exactly equal to ``1e100``. The function
1838 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001839 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1840 is more appropriate depends on the application.
1841
1842.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001843 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001844 cases, Python returns the latter result, in order to preserve that
1845 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1846
Martin Panteraa0da862015-09-23 05:28:13 +00001847.. [#] The Unicode standard distinguishes between :dfn:`code points`
1848 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
1849 While most abstract characters in Unicode are only represented using one
1850 code point, there is a number of abstract characters that can in addition be
1851 represented using a sequence of more than one code point. For example, the
1852 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
1853 as a single :dfn:`precomposed character` at code position U+00C7, or as a
1854 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
1855 LETTER C), followed by a :dfn:`combining character` at code position U+0327
1856 (COMBINING CEDILLA).
1857
1858 The comparison operators on strings compare at the level of Unicode code
1859 points. This may be counter-intuitive to humans. For example,
1860 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1861 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".
1862
1863 To compare strings at the level of abstract characters (that is, in a way
1864 intuitive to humans), use :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001865
Georg Brandl48310cd2009-01-03 21:18:54 +00001866.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001867 descriptors, you may notice seemingly unusual behaviour in certain uses of
1868 the :keyword:`is` operator, like those involving comparisons between instance
1869 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001870
Georg Brandl063f2372010-12-01 15:32:43 +00001871.. [#] The ``%`` operator is also used for string formatting; the same
1872 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001873
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001874.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1875 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.