blob: cf7d05eef6746a49dcbc86b3a4954666ad9e4d60 [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
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200188:keyword:`!for` clause and zero or more :keyword:`!for` or :keyword:`!if` clauses.
Georg Brandl96593ed2007-09-07 14:15:41 +0000189In this case, the elements of the new container are those that would be produced
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200190by considering each of the :keyword:`!for` or :keyword:`!if` clauses a block,
Georg Brandl96593ed2007-09-07 14:15:41 +0000191nesting from left to right, and evaluating the expression to produce an element
192each time the innermost block is reached.
193
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200194However, aside from the iterable expression in the leftmost :keyword:`!for` clause,
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200195the 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
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200198The iterable expression in the leftmost :keyword:`!for` clause is evaluated
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200199directly in the enclosing scope and then passed as an argument to the implictly
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200200nested scope. Subsequent :keyword:`!for` clauses and any filter condition in the
201leftmost :keyword:`!for` clause cannot be evaluated in the enclosing scope as
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200202they 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
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200212Since Python 3.6, in an :keyword:`async def` function, an :keyword:`!async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500213clause may be used to iterate over a :term:`asynchronous iterator`.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200214A comprehension in an :keyword:`!async def` function may consist of either a
215:keyword:`!for` or :keyword:`!async for` clause following the leading
216expression, may contain additional :keyword:`!for` or :keyword:`!async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500217clauses, and may also use :keyword:`await` expressions.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200218If a comprehension contains either :keyword:`!async for` clauses
219or :keyword:`!await` expressions it is called an
Yury Selivanov03660042016-12-15 17:36:05 -0500220: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
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200363leftmost :keyword:`!for` clause is immediately evaluated, so that an error
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200364produced 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.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200366Subsequent :keyword:`!for` clauses and any filter condition in the leftmost
367:keyword:`!for` clause cannot be evaluated in the enclosing scope as they may
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200368depend 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
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200378If a generator expression contains either :keyword:`!async for`
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400379clauses 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
Andrés Delfinobfe18392018-11-07 15:12:12 -0300421 async def agen(): # defines an asynchronous generator function
Yury Selivanov03660042016-12-15 17:36:05 -0500422 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
Andrés Delfinobfe18392018-11-07 15:12:12 -0300504 :pep:`525` - Asynchronous Generators
505 The proposal that expanded on :pep:`492` by adding generator capabilities to
506 coroutine functions.
507
Georg Brandl116aa622007-08-15 14:28:22 +0000508.. index:: object: generator
Yury Selivanov66f88282015-06-24 11:04:15 -0400509.. _generator-methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000510
R David Murray2c1d1d62012-08-17 20:48:59 -0400511Generator-iterator methods
512^^^^^^^^^^^^^^^^^^^^^^^^^^
513
514This subsection describes the methods of a generator iterator. They can
515be used to control the execution of a generator function.
516
517Note that calling any of the generator methods below when the generator
518is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000519
520.. index:: exception: StopIteration
521
522
Georg Brandl96593ed2007-09-07 14:15:41 +0000523.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000524
Georg Brandl96593ed2007-09-07 14:15:41 +0000525 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500526 executed yield expression. When a generator function is resumed with a
527 :meth:`~generator.__next__` method, the current yield expression always
528 evaluates to :const:`None`. The execution then continues to the next yield
529 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300530 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500531 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000532 exception is raised.
533
534 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
535 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000536
537
538.. method:: generator.send(value)
539
540 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500541 *value* argument becomes the result of the current yield expression. The
542 :meth:`send` method returns the next value yielded by the generator, or
543 raises :exc:`StopIteration` if the generator exits without yielding another
544 value. When :meth:`send` is called to start the generator, it must be called
545 with :const:`None` as the argument, because there is no yield expression that
546 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000547
548
549.. method:: generator.throw(type[, value[, traceback]])
550
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700551 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000552 and returns the next value yielded by the generator function. If the generator
553 exits without yielding another value, a :exc:`StopIteration` exception is
554 raised. If the generator function does not catch the passed-in exception, or
555 raises a different exception, then that exception propagates to the caller.
556
557.. index:: exception: GeneratorExit
558
559
560.. method:: generator.close()
561
562 Raises a :exc:`GeneratorExit` at the point where the generator function was
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400563 paused. If the generator function then exits gracefully, is already closed,
564 or raises :exc:`GeneratorExit` (by not catching the exception), close
565 returns to its caller. If the generator yields a value, a
566 :exc:`RuntimeError` is raised. If the generator raises any other exception,
567 it is propagated to the caller. :meth:`close` does nothing if the generator
568 has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000569
Chris Jerdonek2654b862012-12-23 15:31:57 -0800570.. index:: single: yield; examples
571
572Examples
573^^^^^^^^
574
Georg Brandl116aa622007-08-15 14:28:22 +0000575Here is a simple example that demonstrates the behavior of generators and
576generator functions::
577
578 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000579 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000580 ... try:
581 ... while True:
582 ... try:
583 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000584 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000585 ... value = e
586 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000587 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000588 ...
589 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000590 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000591 Execution starts when 'next()' is called for the first time.
592 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000593 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000594 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000595 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000596 2
597 >>> generator.throw(TypeError, "spam")
598 TypeError('spam',)
599 >>> generator.close()
600 Don't forget to clean up when 'close()' is called.
601
Chris Jerdonek2654b862012-12-23 15:31:57 -0800602For examples using ``yield from``, see :ref:`pep-380` in "What's New in
603Python."
604
Yury Selivanov03660042016-12-15 17:36:05 -0500605.. _asynchronous-generator-functions:
606
607Asynchronous generator functions
608^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
609
610The presence of a yield expression in a function or method defined using
611:keyword:`async def` further defines the function as a
612:term:`asynchronous generator` function.
613
614When an asynchronous generator function is called, it returns an
615asynchronous iterator known as an asynchronous generator object.
616That object then controls the execution of the generator function.
617An asynchronous generator object is typically used in an
618:keyword:`async for` statement in a coroutine function analogously to
619how a generator object would be used in a :keyword:`for` statement.
620
621Calling one of the asynchronous generator's methods returns an
622:term:`awaitable` object, and the execution starts when this object
623is awaited on. At that time, the execution proceeds to the first yield
624expression, where it is suspended again, returning the value of
625:token:`expression_list` to the awaiting coroutine. As with a generator,
626suspension means that all local state is retained, including the
627current bindings of local variables, the instruction pointer, the internal
628evaluation stack, and the state of any exception handling. When the execution
629is resumed by awaiting on the next object returned by the asynchronous
630generator's methods, the function can proceed exactly as if the yield
631expression were just another external call. The value of the yield expression
632after resuming depends on the method which resumed the execution. If
633:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
634:meth:`~agen.asend` is used, then the result will be the value passed in to
635that method.
636
637In an asynchronous generator function, yield expressions are allowed anywhere
638in a :keyword:`try` construct. However, if an asynchronous generator is not
639resumed before it is finalized (by reaching a zero reference count or by
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200640being garbage collected), then a yield expression within a :keyword:`!try`
Yury Selivanov03660042016-12-15 17:36:05 -0500641construct could result in a failure to execute pending :keyword:`finally`
642clauses. In this case, it is the responsibility of the event loop or
643scheduler running the asynchronous generator to call the asynchronous
644generator-iterator's :meth:`~agen.aclose` method and run the resulting
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200645coroutine object, thus allowing any pending :keyword:`!finally` clauses
Yury Selivanov03660042016-12-15 17:36:05 -0500646to execute.
647
648To take care of finalization, an event loop should define
649a *finalizer* function which takes an asynchronous generator-iterator
650and presumably calls :meth:`~agen.aclose` and executes the coroutine.
651This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`.
652When first iterated over, an asynchronous generator-iterator will store the
653registered *finalizer* to be called upon finalization. For a reference example
654of a *finalizer* method see the implementation of
655``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`.
656
657The expression ``yield from <expr>`` is a syntax error when used in an
658asynchronous generator function.
659
660.. index:: object: asynchronous-generator
661.. _asynchronous-generator-methods:
662
663Asynchronous generator-iterator methods
664^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
665
666This subsection describes the methods of an asynchronous generator iterator,
667which are used to control the execution of a generator function.
668
669
670.. index:: exception: StopAsyncIteration
671
672.. coroutinemethod:: agen.__anext__()
673
674 Returns an awaitable which when run starts to execute the asynchronous
675 generator or resumes it at the last executed yield expression. When an
676 asynchronous generator function is resumed with a :meth:`~agen.__anext__`
677 method, the current yield expression always evaluates to :const:`None` in
678 the returned awaitable, which when run will continue to the next yield
679 expression. The value of the :token:`expression_list` of the yield
680 expression is the value of the :exc:`StopIteration` exception raised by
681 the completing coroutine. If the asynchronous generator exits without
682 yielding another value, the awaitable instead raises an
683 :exc:`StopAsyncIteration` exception, signalling that the asynchronous
684 iteration has completed.
685
686 This method is normally called implicitly by a :keyword:`async for` loop.
687
688
689.. coroutinemethod:: agen.asend(value)
690
691 Returns an awaitable which when run resumes the execution of the
692 asynchronous generator. As with the :meth:`~generator.send()` method for a
693 generator, this "sends" a value into the asynchronous generator function,
694 and the *value* argument becomes the result of the current yield expression.
695 The awaitable returned by the :meth:`asend` method will return the next
696 value yielded by the generator as the value of the raised
697 :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the
698 asynchronous generator exits without yielding another value. When
699 :meth:`asend` is called to start the asynchronous
700 generator, it must be called with :const:`None` as the argument,
701 because there is no yield expression that could receive the value.
702
703
704.. coroutinemethod:: agen.athrow(type[, value[, traceback]])
705
706 Returns an awaitable that raises an exception of type ``type`` at the point
707 where the asynchronous generator was paused, and returns the next value
708 yielded by the generator function as the value of the raised
709 :exc:`StopIteration` exception. If the asynchronous generator exits
710 without yielding another value, an :exc:`StopAsyncIteration` exception is
711 raised by the awaitable.
712 If the generator function does not catch the passed-in exception, or
delirious-lettuce3378b202017-05-19 14:37:57 -0600713 raises a different exception, then when the awaitable is run that exception
Yury Selivanov03660042016-12-15 17:36:05 -0500714 propagates to the caller of the awaitable.
715
716.. index:: exception: GeneratorExit
717
718
719.. coroutinemethod:: agen.aclose()
720
721 Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
722 the asynchronous generator function at the point where it was paused.
723 If the asynchronous generator function then exits gracefully, is already
724 closed, or raises :exc:`GeneratorExit` (by not catching the exception),
725 then the returned awaitable will raise a :exc:`StopIteration` exception.
726 Any further awaitables returned by subsequent calls to the asynchronous
727 generator will raise a :exc:`StopAsyncIteration` exception. If the
728 asynchronous generator yields a value, a :exc:`RuntimeError` is raised
729 by the awaitable. If the asynchronous generator raises any other exception,
730 it is propagated to the caller of the awaitable. If the asynchronous
731 generator has already exited due to an exception or normal exit, then
732 further calls to :meth:`aclose` will return an awaitable that does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000733
Georg Brandl116aa622007-08-15 14:28:22 +0000734.. _primaries:
735
736Primaries
737=========
738
739.. index:: single: primary
740
741Primaries represent the most tightly bound operations of the language. Their
742syntax is:
743
744.. productionlist::
745 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
746
747
748.. _attribute-references:
749
750Attribute references
751--------------------
752
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300753.. index::
754 pair: attribute; reference
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200755 single: . (dot); attribute reference
Georg Brandl116aa622007-08-15 14:28:22 +0000756
757An attribute reference is a primary followed by a period and a name:
758
759.. productionlist::
760 attributeref: `primary` "." `identifier`
761
762.. index::
763 exception: AttributeError
764 object: module
765 object: list
766
767The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000768references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700769attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500770overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700771the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
772the object produced is determined by the object. Multiple evaluations of the
773same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000774
775
776.. _subscriptions:
777
778Subscriptions
779-------------
780
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300781.. index::
782 single: subscription
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200783 single: [] (square brackets); subscription
Georg Brandl116aa622007-08-15 14:28:22 +0000784
785.. index::
786 object: sequence
787 object: mapping
788 object: string
789 object: tuple
790 object: list
791 object: dictionary
792 pair: sequence; item
793
794A subscription selects an item of a sequence (string, tuple or list) or mapping
795(dictionary) object:
796
797.. productionlist::
798 subscription: `primary` "[" `expression_list` "]"
799
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700800The primary must evaluate to an object that supports subscription (lists or
801dictionaries for example). User-defined objects can support subscription by
802defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000803
804For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000805
806If the primary is a mapping, the expression list must evaluate to an object
807whose value is one of the keys of the mapping, and the subscription selects the
808value in the mapping that corresponds to that key. (The expression list is a
809tuple except if it has exactly one item.)
810
Andrés Delfino4fddd4e2018-06-15 15:24:25 -0300811If the primary is a sequence, the expression list must evaluate to an integer
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000812or a slice (as discussed in the following section).
813
814The formal syntax makes no special provision for negative indices in
815sequences; however, built-in sequences all provide a :meth:`__getitem__`
816method that interprets negative indices by adding the length of the sequence
817to the index (so that ``x[-1]`` selects the last item of ``x``). The
818resulting value must be a nonnegative integer less than the number of items in
819the sequence, and the subscription selects the item whose index is that value
820(counting from zero). Since the support for negative indices and slicing
821occurs in the object's :meth:`__getitem__` method, subclasses overriding
822this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000823
824.. index::
825 single: character
826 pair: string; item
827
828A string's items are characters. A character is not a separate data type but a
829string of exactly one character.
830
831
832.. _slicings:
833
834Slicings
835--------
836
837.. index::
838 single: slicing
839 single: slice
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200840 single: : (colon); slicing
841 single: , (comma); slicing
Georg Brandl116aa622007-08-15 14:28:22 +0000842
843.. index::
844 object: sequence
845 object: string
846 object: tuple
847 object: list
848
849A slicing selects a range of items in a sequence object (e.g., a string, tuple
850or list). Slicings may be used as expressions or as targets in assignment or
851:keyword:`del` statements. The syntax for a slicing:
852
853.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000854 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000855 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000856 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000857 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000858 lower_bound: `expression`
859 upper_bound: `expression`
860 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000861
862There is ambiguity in the formal syntax here: anything that looks like an
863expression list also looks like a slice list, so any subscription can be
864interpreted as a slicing. Rather than further complicating the syntax, this is
865disambiguated by defining that in this case the interpretation as a subscription
866takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000867slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000868
869.. index::
870 single: start (slice object attribute)
871 single: stop (slice object attribute)
872 single: step (slice object attribute)
873
Georg Brandla4c8c472014-10-31 10:38:49 +0100874The semantics for a slicing are as follows. The primary is indexed (using the
875same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000876normal subscription) with a key that is constructed from the slice list, as
877follows. If the slice list contains at least one comma, the key is a tuple
878containing the conversion of the slice items; otherwise, the conversion of the
879lone slice item is the key. The conversion of a slice item that is an
880expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300881object (see section :ref:`types`) whose :attr:`~slice.start`,
882:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
883expressions given as lower bound, upper bound and stride, respectively,
884substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000885
886
Chris Jerdonekb4309942012-12-25 14:54:44 -0800887.. index::
888 object: callable
889 single: call
890 single: argument; call semantics
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200891 single: () (parentheses); call
892 single: , (comma); argument list
893 single: = (equals); in function calls
Chris Jerdonekb4309942012-12-25 14:54:44 -0800894
Georg Brandl116aa622007-08-15 14:28:22 +0000895.. _calls:
896
897Calls
898-----
899
Chris Jerdonekb4309942012-12-25 14:54:44 -0800900A call calls a callable object (e.g., a :term:`function`) with a possibly empty
901series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000902
903.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000904 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Martin Panter0c0da482016-06-12 01:46:50 +0000905 argument_list: `positional_arguments` ["," `starred_and_keywords`]
906 : ["," `keywords_arguments`]
907 : | `starred_and_keywords` ["," `keywords_arguments`]
908 : | `keywords_arguments`
909 positional_arguments: ["*"] `expression` ("," ["*"] `expression`)*
910 starred_and_keywords: ("*" `expression` | `keyword_item`)
911 : ("," "*" `expression` | "," `keyword_item`)*
912 keywords_arguments: (`keyword_item` | "**" `expression`)
Martin Panter7106a512016-12-24 10:20:38 +0000913 : ("," `keyword_item` | "," "**" `expression`)*
Georg Brandl116aa622007-08-15 14:28:22 +0000914 keyword_item: `identifier` "=" `expression`
915
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700916An optional trailing comma may be present after the positional and keyword arguments
917but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000918
Chris Jerdonekb4309942012-12-25 14:54:44 -0800919.. index::
920 single: parameter; call semantics
921
Georg Brandl116aa622007-08-15 14:28:22 +0000922The primary must evaluate to a callable object (user-defined functions, built-in
923functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000924instances, and all objects having a :meth:`__call__` method are callable). All
925argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800926to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000927
928.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000929
930If keyword arguments are present, they are first converted to positional
931arguments, as follows. First, a list of unfilled slots is created for the
932formal parameters. If there are N positional arguments, they are placed in the
933first N slots. Next, for each keyword argument, the identifier is used to
934determine the corresponding slot (if the identifier is the same as the first
935formal parameter name, the first slot is used, and so on). If the slot is
936already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
937the argument is placed in the slot, filling it (even if the expression is
938``None``, it fills the slot). When all arguments have been processed, the slots
939that are still unfilled are filled with the corresponding default value from the
940function definition. (Default values are calculated, once, when the function is
941defined; thus, a mutable object such as a list or dictionary used as default
942value will be shared by all calls that don't specify an argument value for the
943corresponding slot; this should usually be avoided.) If there are any unfilled
944slots for which no default value is specified, a :exc:`TypeError` exception is
945raised. Otherwise, the list of filled slots is used as the argument list for
946the call.
947
Georg Brandl495f7b52009-10-27 15:28:25 +0000948.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000949
Georg Brandl495f7b52009-10-27 15:28:25 +0000950 An implementation may provide built-in functions whose positional parameters
951 do not have names, even if they are 'named' for the purpose of documentation,
952 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000953 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000954 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000955
Georg Brandl116aa622007-08-15 14:28:22 +0000956If there are more positional arguments than there are formal parameter slots, a
957:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
958``*identifier`` is present; in this case, that formal parameter receives a tuple
959containing the excess positional arguments (or an empty tuple if there were no
960excess positional arguments).
961
962If any keyword argument does not correspond to a formal parameter name, a
963:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
964``**identifier`` is present; in this case, that formal parameter receives a
965dictionary containing the excess keyword arguments (using the keywords as keys
966and the argument values as corresponding values), or a (new) empty dictionary if
967there were no excess keyword arguments.
968
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300969.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200970 single: * (asterisk); in function calls
Martin Panter0c0da482016-06-12 01:46:50 +0000971 single: unpacking; in function calls
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300972
Georg Brandl116aa622007-08-15 14:28:22 +0000973If the syntax ``*expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +0000974evaluate to an :term:`iterable`. Elements from these iterables are
975treated as if they were additional positional arguments. For the call
976``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*,
977this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
978*y1*, ..., *yM*, *x3*, *x4*.
Georg Brandl116aa622007-08-15 14:28:22 +0000979
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000980A consequence of this is that although the ``*expression`` syntax may appear
Martin Panter0c0da482016-06-12 01:46:50 +0000981*after* explicit keyword arguments, it is processed *before* the
982keyword arguments (and any ``**expression`` arguments -- see below). So::
Georg Brandl116aa622007-08-15 14:28:22 +0000983
984 >>> def f(a, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300985 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000986 ...
987 >>> f(b=1, *(2,))
988 2 1
989 >>> f(a=1, *(2,))
990 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530991 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000992 TypeError: f() got multiple values for keyword argument 'a'
993 >>> f(1, *(2,))
994 1 2
995
996It is unusual for both keyword arguments and the ``*expression`` syntax to be
997used in the same call, so in practice this confusion does not arise.
998
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300999.. index::
1000 single: **; in function calls
1001
Georg Brandl116aa622007-08-15 14:28:22 +00001002If the syntax ``**expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +00001003evaluate to a :term:`mapping`, the contents of which are treated as
1004additional keyword arguments. If a keyword is already present
1005(as an explicit keyword argument, or from another unpacking),
1006a :exc:`TypeError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001007
1008Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
1009used as positional argument slots or as keyword argument names.
1010
Martin Panter0c0da482016-06-12 01:46:50 +00001011.. versionchanged:: 3.5
1012 Function calls accept any number of ``*`` and ``**`` unpackings,
1013 positional arguments may follow iterable unpackings (``*``),
1014 and keyword arguments may follow dictionary unpackings (``**``).
1015 Originally proposed by :pep:`448`.
1016
Georg Brandl116aa622007-08-15 14:28:22 +00001017A call always returns some value, possibly ``None``, unless it raises an
1018exception. How this value is computed depends on the type of the callable
1019object.
1020
1021If it is---
1022
1023a user-defined function:
1024 .. index::
1025 pair: function; call
1026 triple: user-defined; function; call
1027 object: user-defined function
1028 object: function
1029
1030 The code block for the function is executed, passing it the argument list. The
1031 first thing the code block will do is bind the formal parameters to the
1032 arguments; this is described in section :ref:`function`. When the code block
1033 executes a :keyword:`return` statement, this specifies the return value of the
1034 function call.
1035
1036a built-in function or method:
1037 .. index::
1038 pair: function; call
1039 pair: built-in function; call
1040 pair: method; call
1041 pair: built-in method; call
1042 object: built-in method
1043 object: built-in function
1044 object: method
1045 object: function
1046
1047 The result is up to the interpreter; see :ref:`built-in-funcs` for the
1048 descriptions of built-in functions and methods.
1049
1050a class object:
1051 .. index::
1052 object: class
1053 pair: class object; call
1054
1055 A new instance of that class is returned.
1056
1057a class instance method:
1058 .. index::
1059 object: class instance
1060 object: instance
1061 pair: class instance; call
1062
1063 The corresponding user-defined function is called, with an argument list that is
1064 one longer than the argument list of the call: the instance becomes the first
1065 argument.
1066
1067a class instance:
1068 .. index::
1069 pair: instance; call
1070 single: __call__() (object method)
1071
1072 The class must define a :meth:`__call__` method; the effect is then the same as
1073 if that method was called.
1074
1075
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001076.. index:: keyword: await
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001077.. _await:
1078
1079Await expression
1080================
1081
1082Suspend the execution of :term:`coroutine` on an :term:`awaitable` object.
1083Can only be used inside a :term:`coroutine function`.
1084
1085.. productionlist::
Serhiy Storchakac7cc9852016-05-08 21:59:46 +03001086 await_expr: "await" `primary`
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001087
1088.. versionadded:: 3.5
1089
1090
Georg Brandl116aa622007-08-15 14:28:22 +00001091.. _power:
1092
1093The power operator
1094==================
1095
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001096.. index::
1097 pair: power; operation
1098 operator: **
1099
Georg Brandl116aa622007-08-15 14:28:22 +00001100The power operator binds more tightly than unary operators on its left; it binds
1101less tightly than unary operators on its right. The syntax is:
1102
1103.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001104 power: (`await_expr` | `primary`) ["**" `u_expr`]
Georg Brandl116aa622007-08-15 14:28:22 +00001105
1106Thus, in an unparenthesized sequence of power and unary operators, the operators
1107are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +00001108for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001109
1110The power operator has the same semantics as the built-in :func:`pow` function,
1111when called with two arguments: it yields its left argument raised to the power
1112of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +00001113type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +00001114
Georg Brandl96593ed2007-09-07 14:15:41 +00001115For int operands, the result has the same type as the operands unless the second
1116argument is negative; in that case, all arguments are converted to float and a
1117float result is delivered. For example, ``10**2`` returns ``100``, but
1118``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +00001119
1120Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +00001121Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001122number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001123
1124
1125.. _unary:
1126
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001127Unary arithmetic and bitwise operations
1128=======================================
Georg Brandl116aa622007-08-15 14:28:22 +00001129
1130.. index::
1131 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +00001132 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001133
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001134All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +00001135
1136.. productionlist::
1137 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
1138
1139.. index::
1140 single: negation
1141 single: minus
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001142 single: operator; - (minus)
1143 single: - (minus); unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001144
1145The unary ``-`` (minus) operator yields the negation of its numeric argument.
1146
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001147.. index::
1148 single: plus
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001149 single: operator; + (plus)
1150 single: + (plus); unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001151
1152The unary ``+`` (plus) operator yields its numeric argument unchanged.
1153
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001154.. index::
1155 single: inversion
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001156 operator: ~ (tilde)
Christian Heimesfaf2f632008-01-06 16:59:19 +00001157
Georg Brandl95817b32008-05-11 14:30:18 +00001158The unary ``~`` (invert) operator yields the bitwise inversion of its integer
1159argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
1160applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00001161
1162.. index:: exception: TypeError
1163
1164In all three cases, if the argument does not have the proper type, a
1165:exc:`TypeError` exception is raised.
1166
1167
1168.. _binary:
1169
1170Binary arithmetic operations
1171============================
1172
1173.. index:: triple: binary; arithmetic; operation
1174
1175The binary arithmetic operations have the conventional priority levels. Note
1176that some of these operations also apply to certain non-numeric types. Apart
1177from the power operator, there are only two levels, one for multiplicative
1178operators and one for additive operators:
1179
1180.. productionlist::
Benjamin Petersond51374e2014-04-09 23:55:56 -04001181 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
Andrés Delfinocaccca782018-07-07 17:24:46 -03001182 : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` |
Benjamin Petersond51374e2014-04-09 23:55:56 -04001183 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001184 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
1185
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001186.. index::
1187 single: multiplication
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001188 operator: * (asterisk)
Georg Brandl116aa622007-08-15 14:28:22 +00001189
1190The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +00001191arguments must either both be numbers, or one argument must be an integer and
1192the other must be a sequence. In the former case, the numbers are converted to a
1193common type and then multiplied together. In the latter case, sequence
1194repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001195
Andrés Delfino69511862018-06-15 16:23:00 -03001196.. index::
1197 single: matrix multiplication
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001198 operator: @ (at)
Benjamin Petersond51374e2014-04-09 23:55:56 -04001199
1200The ``@`` (at) operator is intended to be used for matrix multiplication. No
1201builtin Python types implement this operator.
1202
1203.. versionadded:: 3.5
1204
Georg Brandl116aa622007-08-15 14:28:22 +00001205.. index::
1206 exception: ZeroDivisionError
1207 single: division
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001208 operator: / (slash)
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001209 operator: //
Georg Brandl116aa622007-08-15 14:28:22 +00001210
1211The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
1212their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +02001213Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +00001214integer; the result is that of mathematical division with the 'floor' function
1215applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
1216exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001217
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001218.. index::
1219 single: modulo
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001220 operator: % (percent)
Georg Brandl116aa622007-08-15 14:28:22 +00001221
1222The ``%`` (modulo) operator yields the remainder from the division of the first
1223argument by the second. The numeric arguments are first converted to a common
1224type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
1225arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
1226(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
1227result with the same sign as its second operand (or zero); the absolute value of
1228the result is strictly smaller than the absolute value of the second operand
1229[#]_.
1230
Georg Brandl96593ed2007-09-07 14:15:41 +00001231The floor division and modulo operators are connected by the following
1232identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
1233connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
1234x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +00001235
1236In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +00001237also overloaded by string objects to perform old-style string formatting (also
1238known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +00001239Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +00001240
1241The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +00001242function are not defined for complex numbers. Instead, convert to a floating
1243point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +00001244
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001245.. index::
1246 single: addition
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001247 single: operator; + (plus)
1248 single: + (plus); binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001249
Georg Brandl96593ed2007-09-07 14:15:41 +00001250The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001251must either both be numbers or both be sequences of the same type. In the
1252former case, the numbers are converted to a common type and then added together.
1253In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +00001254
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001255.. index::
1256 single: subtraction
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001257 single: operator; - (minus)
1258 single: - (minus); binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001259
1260The ``-`` (subtraction) operator yields the difference of its arguments. The
1261numeric arguments are first converted to a common type.
1262
1263
1264.. _shifting:
1265
1266Shifting operations
1267===================
1268
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001269.. index::
1270 pair: shifting; operation
1271 operator: <<
1272 operator: >>
Georg Brandl116aa622007-08-15 14:28:22 +00001273
1274The shifting operations have lower priority than the arithmetic operations:
1275
1276.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001277 shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001278
Georg Brandl96593ed2007-09-07 14:15:41 +00001279These operators accept integers as arguments. They shift the first argument to
1280the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001281
1282.. index:: exception: ValueError
1283
Georg Brandl0aaae262013-10-08 21:47:18 +02001284A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
1285shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001286
1287
1288.. _bitwise:
1289
Christian Heimesfaf2f632008-01-06 16:59:19 +00001290Binary bitwise operations
1291=========================
Georg Brandl116aa622007-08-15 14:28:22 +00001292
Christian Heimesfaf2f632008-01-06 16:59:19 +00001293.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001294
1295Each of the three bitwise operations has a different priority level:
1296
1297.. productionlist::
1298 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1299 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1300 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1301
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001302.. index::
1303 pair: bitwise; and
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001304 operator: & (ampersand)
Georg Brandl116aa622007-08-15 14:28:22 +00001305
Georg Brandl96593ed2007-09-07 14:15:41 +00001306The ``&`` operator yields the bitwise AND of its arguments, which must be
1307integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001308
1309.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001310 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001311 pair: exclusive; or
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001312 operator: ^ (caret)
Georg Brandl116aa622007-08-15 14:28:22 +00001313
1314The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001315must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001316
1317.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001318 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001319 pair: inclusive; or
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001320 operator: | (vertical bar)
Georg Brandl116aa622007-08-15 14:28:22 +00001321
1322The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001323must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001324
1325
1326.. _comparisons:
1327
1328Comparisons
1329===========
1330
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001331.. index::
1332 single: comparison
1333 pair: C; language
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001334 operator: < (less)
1335 operator: > (greater)
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001336 operator: <=
1337 operator: >=
1338 operator: ==
1339 operator: !=
Georg Brandl116aa622007-08-15 14:28:22 +00001340
1341Unlike C, all comparison operations in Python have the same priority, which is
1342lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1343C, expressions like ``a < b < c`` have the interpretation that is conventional
1344in mathematics:
1345
1346.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001347 comparison: `or_expr` (`comp_operator` `or_expr`)*
Georg Brandl116aa622007-08-15 14:28:22 +00001348 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1349 : | "is" ["not"] | ["not"] "in"
1350
1351Comparisons yield boolean values: ``True`` or ``False``.
1352
1353.. index:: pair: chaining; comparisons
1354
1355Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1356``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1357cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1358
Guido van Rossum04110fb2007-08-24 16:32:05 +00001359Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1360*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1361to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1362evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001363
Guido van Rossum04110fb2007-08-24 16:32:05 +00001364Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001365*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1366pretty).
1367
Martin Panteraa0da862015-09-23 05:28:13 +00001368Value comparisons
1369-----------------
1370
Georg Brandl116aa622007-08-15 14:28:22 +00001371The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
Martin Panteraa0da862015-09-23 05:28:13 +00001372values of two objects. The objects do not need to have the same type.
Georg Brandl116aa622007-08-15 14:28:22 +00001373
Martin Panteraa0da862015-09-23 05:28:13 +00001374Chapter :ref:`objects` states that objects have a value (in addition to type
1375and identity). The value of an object is a rather abstract notion in Python:
1376For example, there is no canonical access method for an object's value. Also,
1377there is no requirement that the value of an object should be constructed in a
1378particular way, e.g. comprised of all its data attributes. Comparison operators
1379implement a particular notion of what the value of an object is. One can think
1380of them as defining the value of an object indirectly, by means of their
1381comparison implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00001382
Martin Panteraa0da862015-09-23 05:28:13 +00001383Because all types are (direct or indirect) subtypes of :class:`object`, they
1384inherit the default comparison behavior from :class:`object`. Types can
1385customize their comparison behavior by implementing
1386:dfn:`rich comparison methods` like :meth:`__lt__`, described in
1387:ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001388
Martin Panteraa0da862015-09-23 05:28:13 +00001389The default behavior for equality comparison (``==`` and ``!=``) is based on
1390the identity of the objects. Hence, equality comparison of instances with the
1391same identity results in equality, and equality comparison of instances with
1392different identities results in inequality. A motivation for this default
1393behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1394implies ``x == y``).
1395
1396A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1397an attempt raises :exc:`TypeError`. A motivation for this default behavior is
1398the lack of a similar invariant as for equality.
1399
1400The behavior of the default equality comparison, that instances with different
1401identities are always unequal, may be in contrast to what types will need that
1402have a sensible definition of object value and value-based equality. Such
1403types will need to customize their comparison behavior, and in fact, a number
1404of built-in types have done that.
1405
1406The following list describes the comparison behavior of the most important
1407built-in types.
1408
1409* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1410 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
1411 compared within and across their types, with the restriction that complex
1412 numbers do not support order comparison. Within the limits of the types
1413 involved, they compare mathematically (algorithmically) correct without loss
1414 of precision.
1415
Tony Fluryad8a0002018-09-14 18:48:50 +01001416 The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are
1417 special. Any ordered comparison of a number to a not-a-number value is false.
1418 A counter-intuitive implication is that not-a-number values are not equal to
1419 themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3``, ``x
1420 == x``, ``x != x`` are all false. This behavior is compliant with IEEE 754.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001421
Martin Panteraa0da862015-09-23 05:28:13 +00001422* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
1423 compared within and across their types. They compare lexicographically using
1424 the numeric values of their elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001425
Martin Panteraa0da862015-09-23 05:28:13 +00001426* Strings (instances of :class:`str`) compare lexicographically using the
1427 numerical Unicode code points (the result of the built-in function
1428 :func:`ord`) of their characters. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001429
Martin Panteraa0da862015-09-23 05:28:13 +00001430 Strings and binary sequences cannot be directly compared.
Georg Brandl116aa622007-08-15 14:28:22 +00001431
Martin Panteraa0da862015-09-23 05:28:13 +00001432* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can
1433 be compared only within each of their types, with the restriction that ranges
1434 do not support order comparison. Equality comparison across these types
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +02001435 results in inequality, and ordering comparison across these types raises
Martin Panteraa0da862015-09-23 05:28:13 +00001436 :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001437
Martin Panteraa0da862015-09-23 05:28:13 +00001438 Sequences compare lexicographically using comparison of corresponding
1439 elements, whereby reflexivity of the elements is enforced.
Georg Brandl116aa622007-08-15 14:28:22 +00001440
Martin Panteraa0da862015-09-23 05:28:13 +00001441 In enforcing reflexivity of elements, the comparison of collections assumes
1442 that for a collection element ``x``, ``x == x`` is always true. Based on
1443 that assumption, element identity is compared first, and element comparison
1444 is performed only for distinct elements. This approach yields the same
1445 result as a strict element comparison would, if the compared elements are
1446 reflexive. For non-reflexive elements, the result is different than for
1447 strict element comparison, and may be surprising: The non-reflexive
1448 not-a-number values for example result in the following comparison behavior
1449 when used in a list::
1450
1451 >>> nan = float('NaN')
1452 >>> nan is nan
1453 True
1454 >>> nan == nan
1455 False <-- the defined non-reflexive behavior of NaN
1456 >>> [nan] == [nan]
1457 True <-- list enforces reflexivity and tests identity first
1458
1459 Lexicographical comparison between built-in collections works as follows:
1460
1461 - For two collections to compare equal, they must be of the same type, have
1462 the same length, and each pair of corresponding elements must compare
1463 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1464 same).
1465
1466 - Collections that support order comparison are ordered the same as their
1467 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same
1468 value as ``x <= y``). If a corresponding element does not exist, the
1469 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1470 true).
1471
1472* Mappings (instances of :class:`dict`) compare equal if and only if they have
cocoatomocdcac032017-03-31 14:48:49 +09001473 equal `(key, value)` pairs. Equality comparison of the keys and values
Martin Panteraa0da862015-09-23 05:28:13 +00001474 enforces reflexivity.
1475
1476 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
1477
1478* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within
1479 and across their types.
1480
1481 They define order
1482 comparison operators to mean subset and superset tests. Those relations do
1483 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}``
1484 are not equal, nor subsets of one another, nor supersets of one
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001485 another). Accordingly, sets are not appropriate arguments for functions
Martin Panteraa0da862015-09-23 05:28:13 +00001486 which depend on total ordering (for example, :func:`min`, :func:`max`, and
1487 :func:`sorted` produce undefined results given a list of sets as inputs).
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001488
Martin Panteraa0da862015-09-23 05:28:13 +00001489 Comparison of sets enforces reflexivity of its elements.
Georg Brandl116aa622007-08-15 14:28:22 +00001490
Martin Panteraa0da862015-09-23 05:28:13 +00001491* Most other built-in types have no comparison methods implemented, so they
1492 inherit the default comparison behavior.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001493
Martin Panteraa0da862015-09-23 05:28:13 +00001494User-defined classes that customize their comparison behavior should follow
1495some consistency rules, if possible:
1496
1497* Equality comparison should be reflexive.
1498 In other words, identical objects should compare equal:
1499
1500 ``x is y`` implies ``x == y``
1501
1502* Comparison should be symmetric.
1503 In other words, the following expressions should have the same result:
1504
1505 ``x == y`` and ``y == x``
1506
1507 ``x != y`` and ``y != x``
1508
1509 ``x < y`` and ``y > x``
1510
1511 ``x <= y`` and ``y >= x``
1512
1513* Comparison should be transitive.
1514 The following (non-exhaustive) examples illustrate that:
1515
1516 ``x > y and y > z`` implies ``x > z``
1517
1518 ``x < y and y <= z`` implies ``x < z``
1519
1520* Inverse comparison should result in the boolean negation.
1521 In other words, the following expressions should have the same result:
1522
1523 ``x == y`` and ``not x != y``
1524
1525 ``x < y`` and ``not x >= y`` (for total ordering)
1526
1527 ``x > y`` and ``not x <= y`` (for total ordering)
1528
1529 The last two expressions apply to totally ordered collections (e.g. to
1530 sequences, but not to sets or mappings). See also the
1531 :func:`~functools.total_ordering` decorator.
1532
Martin Panter8dbb0ca2017-01-29 10:00:23 +00001533* The :func:`hash` result should be consistent with equality.
1534 Objects that are equal should either have the same hash value,
1535 or be marked as unhashable.
1536
Martin Panteraa0da862015-09-23 05:28:13 +00001537Python does not enforce these consistency rules. In fact, the not-a-number
1538values are an example for not following these rules.
1539
1540
1541.. _in:
1542.. _not in:
Georg Brandl495f7b52009-10-27 15:28:25 +00001543.. _membership-test-details:
1544
Martin Panteraa0da862015-09-23 05:28:13 +00001545Membership test operations
1546--------------------------
1547
Georg Brandl96593ed2007-09-07 14:15:41 +00001548The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301549s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
1550``x not in s`` returns the negation of ``x in s``. All built-in sequences and
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001551set types support this as well as dictionary, for which :keyword:`!in` tests
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301552whether the dictionary has a given key. For container types such as list, tuple,
1553set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001554to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001555
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301556For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
Georg Brandl4b491312007-08-31 09:22:56 +00001557substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1558always considered to be a substring of any other string, so ``"" in "abc"`` will
1559return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001560
Georg Brandl116aa622007-08-15 14:28:22 +00001561For user-defined classes which define the :meth:`__contains__` method, ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301562y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and
1563``False`` otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001564
Georg Brandl495f7b52009-10-27 15:28:25 +00001565For user-defined classes which do not define :meth:`__contains__` but do define
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301566:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z`` with ``x == z`` is
Georg Brandl495f7b52009-10-27 15:28:25 +00001567produced while iterating over ``y``. If an exception is raised during the
1568iteration, it is as if :keyword:`in` raised that exception.
1569
1570Lastly, the old-style iteration protocol is tried: if a class defines
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301571:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
Georg Brandl116aa622007-08-15 14:28:22 +00001572integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001573raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001574if :keyword:`in` raised that exception).
1575
1576.. index::
1577 operator: in
1578 operator: not in
1579 pair: membership; test
1580 object: sequence
1581
1582The operator :keyword:`not in` is defined to have the inverse true value of
1583:keyword:`in`.
1584
1585.. index::
1586 operator: is
1587 operator: is not
1588 pair: identity; test
1589
Martin Panteraa0da862015-09-23 05:28:13 +00001590
1591.. _is:
1592.. _is not:
1593
1594Identity comparisons
1595--------------------
1596
Georg Brandl116aa622007-08-15 14:28:22 +00001597The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
Raymond Hettinger06e18a72016-09-11 17:23:49 -07001598is y`` is true if and only if *x* and *y* are the same object. Object identity
1599is determined using the :meth:`id` function. ``x is not y`` yields the inverse
1600truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001601
1602
1603.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001604.. _and:
1605.. _or:
1606.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001607
1608Boolean operations
1609==================
1610
1611.. index::
1612 pair: Conditional; expression
1613 pair: Boolean; operation
1614
Georg Brandl116aa622007-08-15 14:28:22 +00001615.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001616 or_test: `and_test` | `or_test` "or" `and_test`
1617 and_test: `not_test` | `and_test` "and" `not_test`
1618 not_test: `comparison` | "not" `not_test`
1619
1620In the context of Boolean operations, and also when expressions are used by
1621control flow statements, the following values are interpreted as false:
1622``False``, ``None``, numeric zero of all types, and empty strings and containers
1623(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001624other values are interpreted as true. User-defined objects can customize their
1625truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001626
1627.. index:: operator: not
1628
1629The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1630otherwise.
1631
Georg Brandl116aa622007-08-15 14:28:22 +00001632.. index:: operator: and
1633
1634The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1635returned; otherwise, *y* is evaluated and the resulting value is returned.
1636
1637.. index:: operator: or
1638
1639The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1640returned; otherwise, *y* is evaluated and the resulting value is returned.
1641
Andre Delfino55f41e42018-12-05 16:45:30 -03001642Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
Georg Brandl116aa622007-08-15 14:28:22 +00001643they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001644argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001645replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001646the desired value. Because :keyword:`not` has to create a new value, it
1647returns a boolean value regardless of the type of its argument
1648(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001649
1650
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001651.. _if_expr:
1652
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001653Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001654=======================
1655
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001656.. index::
1657 pair: conditional; expression
1658 pair: ternary; operator
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001659 single: if; conditional expression
1660 single: else; conditional expression
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001661
1662.. productionlist::
1663 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001664 expression: `conditional_expression` | `lambda_expr`
1665 expression_nocond: `or_test` | `lambda_expr_nocond`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001666
1667Conditional expressions (sometimes called a "ternary operator") have the lowest
1668priority of all Python operations.
1669
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001670The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1671If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001672evaluated and its value is returned.
1673
1674See :pep:`308` for more details about conditional expressions.
1675
1676
Georg Brandl116aa622007-08-15 14:28:22 +00001677.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001678.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001679
1680Lambdas
1681=======
1682
1683.. index::
1684 pair: lambda; expression
1685 pair: lambda; form
1686 pair: anonymous; function
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001687 single: : (colon); lambda expression
Georg Brandl116aa622007-08-15 14:28:22 +00001688
1689.. productionlist::
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001690 lambda_expr: "lambda" [`parameter_list`] ":" `expression`
1691 lambda_expr_nocond: "lambda" [`parameter_list`] ":" `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001692
Zachary Ware2f78b842014-06-03 09:32:40 -05001693Lambda expressions (sometimes called lambda forms) are used to create anonymous
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001694functions. The expression ``lambda parameters: expression`` yields a function
Martin Panter1050d2d2016-07-26 11:18:21 +02001695object. The unnamed object behaves like a function object defined with:
1696
1697.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +00001698
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001699 def <lambda>(parameters):
Georg Brandl116aa622007-08-15 14:28:22 +00001700 return expression
1701
1702See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001703functions created with lambda expressions cannot contain statements or
1704annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001705
Georg Brandl116aa622007-08-15 14:28:22 +00001706
1707.. _exprlists:
1708
1709Expression lists
1710================
1711
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001712.. index::
1713 pair: expression; list
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001714 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +00001715
1716.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001717 expression_list: `expression` ("," `expression`)* [","]
1718 starred_list: `starred_item` ("," `starred_item`)* [","]
1719 starred_expression: `expression` | (`starred_item` ",")* [`starred_item`]
Martin Panter0c0da482016-06-12 01:46:50 +00001720 starred_item: `expression` | "*" `or_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001721
1722.. index:: object: tuple
1723
Martin Panter0c0da482016-06-12 01:46:50 +00001724Except when part of a list or set display, an expression list
1725containing at least one comma yields a tuple. The length of
Georg Brandl116aa622007-08-15 14:28:22 +00001726the tuple is the number of expressions in the list. The expressions are
1727evaluated from left to right.
1728
Martin Panter0c0da482016-06-12 01:46:50 +00001729.. index::
1730 pair: iterable; unpacking
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001731 single: * (asterisk); in expression lists
Martin Panter0c0da482016-06-12 01:46:50 +00001732
1733An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be
1734an :term:`iterable`. The iterable is expanded into a sequence of items,
1735which are included in the new tuple, list, or set, at the site of
1736the unpacking.
1737
1738.. versionadded:: 3.5
1739 Iterable unpacking in expression lists, originally proposed by :pep:`448`.
1740
Georg Brandl116aa622007-08-15 14:28:22 +00001741.. index:: pair: trailing; comma
1742
1743The trailing comma is required only to create a single tuple (a.k.a. a
1744*singleton*); it is optional in all other cases. A single expression without a
1745trailing comma doesn't create a tuple, but rather yields the value of that
1746expression. (To create an empty tuple, use an empty pair of parentheses:
1747``()``.)
1748
1749
1750.. _evalorder:
1751
1752Evaluation order
1753================
1754
1755.. index:: pair: evaluation; order
1756
Georg Brandl96593ed2007-09-07 14:15:41 +00001757Python evaluates expressions from left to right. Notice that while evaluating
1758an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001759
1760In the following lines, expressions will be evaluated in the arithmetic order of
1761their suffixes::
1762
1763 expr1, expr2, expr3, expr4
1764 (expr1, expr2, expr3, expr4)
1765 {expr1: expr2, expr3: expr4}
1766 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001767 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001768 expr3, expr4 = expr1, expr2
1769
1770
1771.. _operator-summary:
1772
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001773Operator precedence
1774===================
Georg Brandl116aa622007-08-15 14:28:22 +00001775
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001776.. index::
1777 pair: operator; precedence
Georg Brandl116aa622007-08-15 14:28:22 +00001778
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001779The following table summarizes the operator precedence in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001780precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001781the same box have the same precedence. Unless the syntax is explicitly given,
1782operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001783exponentiation, which groups from right to left).
1784
1785Note that comparisons, membership tests, and identity tests, all have the same
1786precedence and have a left-to-right chaining feature as described in the
1787:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001788
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001789
1790+-----------------------------------------------+-------------------------------------+
1791| Operator | Description |
1792+===============================================+=====================================+
1793| :keyword:`lambda` | Lambda expression |
1794+-----------------------------------------------+-------------------------------------+
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001795| :keyword:`if <if_expr>` -- :keyword:`!else` | Conditional expression |
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001796+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001797| :keyword:`or` | Boolean OR |
1798+-----------------------------------------------+-------------------------------------+
1799| :keyword:`and` | Boolean AND |
1800+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001801| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001802+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001803| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001804| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001805| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001806+-----------------------------------------------+-------------------------------------+
1807| ``|`` | Bitwise OR |
1808+-----------------------------------------------+-------------------------------------+
1809| ``^`` | Bitwise XOR |
1810+-----------------------------------------------+-------------------------------------+
1811| ``&`` | Bitwise AND |
1812+-----------------------------------------------+-------------------------------------+
1813| ``<<``, ``>>`` | Shifts |
1814+-----------------------------------------------+-------------------------------------+
1815| ``+``, ``-`` | Addition and subtraction |
1816+-----------------------------------------------+-------------------------------------+
Benjamin Petersond51374e2014-04-09 23:55:56 -04001817| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
svelankar9b47af62017-09-17 20:56:16 -04001818| | multiplication, division, floor |
1819| | division, remainder [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001820+-----------------------------------------------+-------------------------------------+
1821| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1822+-----------------------------------------------+-------------------------------------+
1823| ``**`` | Exponentiation [#]_ |
1824+-----------------------------------------------+-------------------------------------+
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001825| :keyword:`await` ``x`` | Await expression |
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001826+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001827| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1828| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1829+-----------------------------------------------+-------------------------------------+
1830| ``(expressions...)``, | Binding or tuple display, |
1831| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001832| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001833| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001834+-----------------------------------------------+-------------------------------------+
1835
Georg Brandl116aa622007-08-15 14:28:22 +00001836
1837.. rubric:: Footnotes
1838
Georg Brandl116aa622007-08-15 14:28:22 +00001839.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1840 true numerically due to roundoff. For example, and assuming a platform on which
1841 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1842 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001843 1e100``, which is numerically exactly equal to ``1e100``. The function
1844 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001845 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1846 is more appropriate depends on the application.
1847
1848.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001849 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001850 cases, Python returns the latter result, in order to preserve that
1851 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1852
Martin Panteraa0da862015-09-23 05:28:13 +00001853.. [#] The Unicode standard distinguishes between :dfn:`code points`
1854 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
1855 While most abstract characters in Unicode are only represented using one
1856 code point, there is a number of abstract characters that can in addition be
1857 represented using a sequence of more than one code point. For example, the
1858 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
1859 as a single :dfn:`precomposed character` at code position U+00C7, or as a
1860 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
1861 LETTER C), followed by a :dfn:`combining character` at code position U+0327
1862 (COMBINING CEDILLA).
1863
1864 The comparison operators on strings compare at the level of Unicode code
1865 points. This may be counter-intuitive to humans. For example,
1866 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1867 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".
1868
1869 To compare strings at the level of abstract characters (that is, in a way
1870 intuitive to humans), use :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001871
Georg Brandl48310cd2009-01-03 21:18:54 +00001872.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001873 descriptors, you may notice seemingly unusual behaviour in certain uses of
1874 the :keyword:`is` operator, like those involving comparisons between instance
1875 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001876
Georg Brandl063f2372010-12-01 15:32:43 +00001877.. [#] The ``%`` operator is also used for string formatting; the same
1878 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001879
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001880.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1881 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.