blob: f1f19c3f02d3907c4538e7b116a9a07bf89f0c72 [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
Miss Islington (bot)c0534022020-09-18 00:27:21 -070016.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +000017 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
Mathieu Dupuyc49016e2020-03-30 23:28:25 +020031arguments 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
Miss Islington (bot)c0534022020-09-18 00:27:21 -070057.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +000058 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
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700106.. productionlist:: python-grammar
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
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700137.. productionlist:: python-grammar
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
divyag9778a9102019-05-13 08:05:20 -0500147immutable, the same rules as for literals apply (i.e., two occurrences of the empty
Georg Brandl116aa622007-08-15 14:28:22 +0000148tuple may or may not yield the same object).
149
150.. index::
Andre Delfinodc269972019-09-11 10:16:11 -0300151 single: comma
152 single: , (comma)
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154Note that tuples are not formed by the parentheses, but rather by use of the
155comma operator. The exception is the empty tuple, for which parentheses *are*
156required --- allowing unparenthesized "nothing" in expressions would cause
157ambiguities and allow common typos to pass uncaught.
158
159
Georg Brandl96593ed2007-09-07 14:15:41 +0000160.. _comprehensions:
161
162Displays for lists, sets and dictionaries
163-----------------------------------------
164
165For constructing a list, a set or a dictionary Python provides special syntax
166called "displays", each of them in two flavors:
167
168* either the container contents are listed explicitly, or
169
170* they are computed via a set of looping and filtering instructions, called a
171 :dfn:`comprehension`.
172
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300173.. index::
174 single: for; in comprehensions
175 single: if; in comprehensions
176 single: async for; in comprehensions
177
Georg Brandl96593ed2007-09-07 14:15:41 +0000178Common syntax elements for comprehensions are:
179
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700180.. productionlist:: python-grammar
Brandt Bucher8bae2192020-03-05 21:19:22 -0800181 comprehension: `assignment_expression` `comp_for`
Serhiy Storchakad08972f2018-04-11 19:15:51 +0300182 comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`]
Georg Brandl96593ed2007-09-07 14:15:41 +0000183 comp_iter: `comp_for` | `comp_if`
184 comp_if: "if" `expression_nocond` [`comp_iter`]
185
186The comprehension consists of a single expression followed by at least one
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200187:keyword:`!for` clause and zero or more :keyword:`!for` or :keyword:`!if` clauses.
Georg Brandl96593ed2007-09-07 14:15:41 +0000188In this case, the elements of the new container are those that would be produced
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200189by considering each of the :keyword:`!for` or :keyword:`!if` clauses a block,
Georg Brandl96593ed2007-09-07 14:15:41 +0000190nesting from left to right, and evaluating the expression to produce an element
191each time the innermost block is reached.
192
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200193However, aside from the iterable expression in the leftmost :keyword:`!for` clause,
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200194the comprehension is executed in a separate implicitly nested scope. This ensures
195that names assigned to in the target list don't "leak" into the enclosing scope.
196
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200197The iterable expression in the leftmost :keyword:`!for` clause is evaluated
Johnny Gérard4ef9b8e2019-05-13 05:39:32 +0200198directly in the enclosing scope and then passed as an argument to the implicitly
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200199nested scope. Subsequent :keyword:`!for` clauses and any filter condition in the
200leftmost :keyword:`!for` clause cannot be evaluated in the enclosing scope as
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200201they may depend on the values obtained from the leftmost iterable. For example:
202``[x*y for x in range(10) for y in range(x, x+10)]``.
203
204To ensure the comprehension always results in a container of the appropriate
205type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200206nested scope.
Georg Brandl02c30562007-09-07 17:52:53 +0000207
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300208.. index::
209 single: await; in comprehensions
210
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200211Since Python 3.6, in an :keyword:`async def` function, an :keyword:`!async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500212clause may be used to iterate over a :term:`asynchronous iterator`.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200213A comprehension in an :keyword:`!async def` function may consist of either a
214:keyword:`!for` or :keyword:`!async for` clause following the leading
215expression, may contain additional :keyword:`!for` or :keyword:`!async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500216clauses, and may also use :keyword:`await` expressions.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200217If a comprehension contains either :keyword:`!async for` clauses
218or :keyword:`!await` expressions it is called an
Yury Selivanov03660042016-12-15 17:36:05 -0500219:dfn:`asynchronous comprehension`. An asynchronous comprehension may
220suspend the execution of the coroutine function in which it appears.
221See also :pep:`530`.
Georg Brandl96593ed2007-09-07 14:15:41 +0000222
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200223.. versionadded:: 3.6
224 Asynchronous comprehensions were introduced.
225
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200226.. versionchanged:: 3.8
227 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200228
229
Georg Brandl116aa622007-08-15 14:28:22 +0000230.. _lists:
231
232List displays
233-------------
234
235.. index::
236 pair: list; display
237 pair: list; comprehensions
Georg Brandl96593ed2007-09-07 14:15:41 +0000238 pair: empty; list
239 object: list
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200240 single: [] (square brackets); list expression
241 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243A list display is a possibly empty series of expressions enclosed in square
244brackets:
245
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700246.. productionlist:: python-grammar
Martin Panter0c0da482016-06-12 01:46:50 +0000247 list_display: "[" [`starred_list` | `comprehension`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000248
Georg Brandl96593ed2007-09-07 14:15:41 +0000249A list display yields a new list object, the contents being specified by either
250a list of expressions or a comprehension. When a comma-separated list of
251expressions is supplied, its elements are evaluated from left to right and
252placed into the list object in that order. When a comprehension is supplied,
253the list is constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255
Georg Brandl96593ed2007-09-07 14:15:41 +0000256.. _set:
Georg Brandl116aa622007-08-15 14:28:22 +0000257
Georg Brandl96593ed2007-09-07 14:15:41 +0000258Set displays
259------------
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300261.. index::
262 pair: set; display
263 object: set
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200264 single: {} (curly brackets); set expression
265 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000266
Georg Brandl96593ed2007-09-07 14:15:41 +0000267A set display is denoted by curly braces and distinguishable from dictionary
268displays by the lack of colons separating keys and values:
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700270.. productionlist:: python-grammar
Martin Panter0c0da482016-06-12 01:46:50 +0000271 set_display: "{" (`starred_list` | `comprehension`) "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Georg Brandl96593ed2007-09-07 14:15:41 +0000273A set display yields a new mutable set object, the contents being specified by
274either a sequence of expressions or a comprehension. When a comma-separated
275list of expressions is supplied, its elements are evaluated from left to right
276and added to the set object. When a comprehension is supplied, the set is
277constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Georg Brandl528cdb12008-09-21 07:09:51 +0000279An empty set cannot be constructed with ``{}``; this literal constructs an empty
280dictionary.
Christian Heimes78644762008-03-04 23:39:23 +0000281
282
Georg Brandl116aa622007-08-15 14:28:22 +0000283.. _dict:
284
285Dictionary displays
286-------------------
287
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300288.. index::
289 pair: dictionary; display
290 key, datum, key/datum pair
291 object: dictionary
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200292 single: {} (curly brackets); dictionary expression
293 single: : (colon); in dictionary expressions
294 single: , (comma); in dictionary displays
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296A dictionary display is a possibly empty series of key/datum pairs enclosed in
297curly braces:
298
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700299.. productionlist:: python-grammar
Georg Brandl96593ed2007-09-07 14:15:41 +0000300 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000301 key_datum_list: `key_datum` ("," `key_datum`)* [","]
Martin Panter0c0da482016-06-12 01:46:50 +0000302 key_datum: `expression` ":" `expression` | "**" `or_expr`
Georg Brandl96593ed2007-09-07 14:15:41 +0000303 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305A dictionary display yields a new dictionary object.
306
Georg Brandl96593ed2007-09-07 14:15:41 +0000307If a comma-separated sequence of key/datum pairs is given, they are evaluated
308from left to right to define the entries of the dictionary: each key object is
309used as a key into the dictionary to store the corresponding datum. This means
310that you can specify the same key multiple times in the key/datum list, and the
311final dictionary's value for that key will be the last one given.
312
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300313.. index::
314 unpacking; dictionary
315 single: **; in dictionary displays
Martin Panter0c0da482016-06-12 01:46:50 +0000316
317A double asterisk ``**`` denotes :dfn:`dictionary unpacking`.
318Its operand must be a :term:`mapping`. Each mapping item is added
319to the new dictionary. Later values replace values already set by
320earlier key/datum pairs and earlier dictionary unpackings.
321
322.. versionadded:: 3.5
323 Unpacking into dictionary displays, originally proposed by :pep:`448`.
324
Georg Brandl96593ed2007-09-07 14:15:41 +0000325A dict comprehension, in contrast to list and set comprehensions, needs two
326expressions separated with a colon followed by the usual "for" and "if" clauses.
327When the comprehension is run, the resulting key and value elements are inserted
328in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000331 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000332
333Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000334:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000335all mutable objects.) Clashes between duplicate keys are not detected; the last
336datum (textually rightmost in the display) stored for a given key value
337prevails.
338
Jörn Heisslerc8a35412019-06-22 16:40:55 +0200339.. versionchanged:: 3.8
340 Prior to Python 3.8, in dict comprehensions, the evaluation order of key
341 and value was not well-defined. In CPython, the value was evaluated before
342 the key. Starting with 3.8, the key is evaluated before the value, as
343 proposed by :pep:`572`.
344
Georg Brandl116aa622007-08-15 14:28:22 +0000345
Georg Brandl96593ed2007-09-07 14:15:41 +0000346.. _genexpr:
347
348Generator expressions
349---------------------
350
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300351.. index::
352 pair: generator; expression
353 object: generator
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200354 single: () (parentheses); generator expression
Georg Brandl96593ed2007-09-07 14:15:41 +0000355
356A generator expression is a compact generator notation in parentheses:
357
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700358.. productionlist:: python-grammar
Georg Brandl96593ed2007-09-07 14:15:41 +0000359 generator_expression: "(" `expression` `comp_for` ")"
360
361A generator expression yields a new generator object. Its syntax is the same as
362for comprehensions, except that it is enclosed in parentheses instead of
363brackets or curly braces.
364
365Variables used in the generator expression are evaluated lazily when the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700366:meth:`~generator.__next__` method is called for the generator object (in the same
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200367fashion as normal generators). However, the iterable expression in the
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200368leftmost :keyword:`!for` clause is immediately evaluated, so that an error
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200369produced by it will be emitted at the point where the generator expression
370is defined, rather than at the point where the first value is retrieved.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200371Subsequent :keyword:`!for` clauses and any filter condition in the leftmost
372:keyword:`!for` clause cannot be evaluated in the enclosing scope as they may
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200373depend on the values obtained from the leftmost iterable. For example:
374``(x*y for x in range(10) for y in range(x, x+10))``.
Georg Brandl96593ed2007-09-07 14:15:41 +0000375
376The parentheses can be omitted on calls with only one argument. See section
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700377:ref:`calls` for details.
Georg Brandl96593ed2007-09-07 14:15:41 +0000378
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200379To avoid interfering with the expected operation of the generator expression
380itself, ``yield`` and ``yield from`` expressions are prohibited in the
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200381implicitly defined generator.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200382
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200383If a generator expression contains either :keyword:`!async for`
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400384clauses or :keyword:`await` expressions it is called an
385:dfn:`asynchronous generator expression`. An asynchronous generator
386expression returns a new asynchronous generator object,
387which is an asynchronous iterator (see :ref:`async-iterators`).
388
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200389.. versionadded:: 3.6
390 Asynchronous generator expressions were introduced.
391
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400392.. versionchanged:: 3.7
393 Prior to Python 3.7, asynchronous generator expressions could
394 only appear in :keyword:`async def` coroutines. Starting
395 with 3.7, any function can use asynchronous generator expressions.
Georg Brandl96593ed2007-09-07 14:15:41 +0000396
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200397.. versionchanged:: 3.8
398 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200399
400
Georg Brandl116aa622007-08-15 14:28:22 +0000401.. _yieldexpr:
402
403Yield expressions
404-----------------
405
406.. index::
407 keyword: yield
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300408 keyword: from
Georg Brandl116aa622007-08-15 14:28:22 +0000409 pair: yield; expression
410 pair: generator; function
411
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700412.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000413 yield_atom: "(" `yield_expression` ")"
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000414 yield_expression: "yield" [`expression_list` | "from" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Yury Selivanov03660042016-12-15 17:36:05 -0500416The yield expression is used when defining a :term:`generator` function
417or an :term:`asynchronous generator` function and
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500418thus can only be used in the body of a function definition. Using a yield
Yury Selivanov03660042016-12-15 17:36:05 -0500419expression in a function's body causes that function to be a generator,
420and using it in an :keyword:`async def` function's body causes that
421coroutine function to be an asynchronous generator. For example::
422
423 def gen(): # defines a generator function
424 yield 123
425
Andrés Delfinobfe18392018-11-07 15:12:12 -0300426 async def agen(): # defines an asynchronous generator function
Yury Selivanov03660042016-12-15 17:36:05 -0500427 yield 123
428
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200429Due to their side effects on the containing scope, ``yield`` expressions
430are not permitted as part of the implicitly defined scopes used to
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200431implement comprehensions and generator expressions.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200432
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200433.. versionchanged:: 3.8
434 Yield expressions prohibited in the implicitly nested scopes used to
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200435 implement comprehensions and generator expressions.
436
Yury Selivanov03660042016-12-15 17:36:05 -0500437Generator functions are described below, while asynchronous generator
438functions are described separately in section
439:ref:`asynchronous-generator-functions`.
Georg Brandl116aa622007-08-15 14:28:22 +0000440
441When a generator function is called, it returns an iterator known as a
Guido van Rossumd0150ad2015-05-05 12:02:01 -0700442generator. That generator then controls the execution of the generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000443The execution starts when one of the generator's methods is called. At that
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500444time, the execution proceeds to the first yield expression, where it is
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700445suspended again, returning the value of :token:`expression_list` to the generator's
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500446caller. By suspended, we mean that all local state is retained, including the
Ethan Furman2f825af2015-01-14 22:25:27 -0800447current bindings of local variables, the instruction pointer, the internal
448evaluation stack, and the state of any exception handling. When the execution
449is resumed by calling one of the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500450generator's methods, the function can proceed exactly as if the yield expression
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700451were just another external call. The value of the yield expression after
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500452resuming depends on the method which resumed the execution. If
453:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or
454the :func:`next` builtin) then the result is :const:`None`. Otherwise, if
455:meth:`~generator.send` is used, then the result will be the value passed in to
456that method.
Georg Brandl116aa622007-08-15 14:28:22 +0000457
458.. index:: single: coroutine
459
460All of this makes generator functions quite similar to coroutines; they yield
461multiple times, they have more than one entry point and their execution can be
462suspended. The only difference is that a generator function cannot control
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700463where the execution should continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000464transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000465
Ethan Furman2f825af2015-01-14 22:25:27 -0800466Yield expressions are allowed anywhere in a :keyword:`try` construct. If the
467generator is not resumed before it is
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500468finalized (by reaching a zero reference count or by being garbage collected),
469the generator-iterator's :meth:`~generator.close` method will be called,
470allowing any pending :keyword:`finally` clauses to execute.
Georg Brandl02c30562007-09-07 17:52:53 +0000471
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300472.. index::
473 single: from; yield from expression
474
Nick Coghlan0ed80192012-01-14 14:43:24 +1000475When ``yield from <expr>`` is used, it treats the supplied expression as
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000476a subiterator. All values produced by that subiterator are passed directly
477to the caller of the current generator's methods. Any values passed in with
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300478:meth:`~generator.send` and any exceptions passed in with
479:meth:`~generator.throw` are passed to the underlying iterator if it has the
480appropriate methods. If this is not the case, then :meth:`~generator.send`
481will raise :exc:`AttributeError` or :exc:`TypeError`, while
482:meth:`~generator.throw` will just raise the passed in exception immediately.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000483
484When the underlying iterator is complete, the :attr:`~StopIteration.value`
485attribute of the raised :exc:`StopIteration` instance becomes the value of
486the yield expression. It can be either set explicitly when raising
divyag9778a9102019-05-13 08:05:20 -0500487:exc:`StopIteration`, or automatically when the subiterator is a generator
488(by returning a value from the subgenerator).
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000489
Nick Coghlan0ed80192012-01-14 14:43:24 +1000490 .. versionchanged:: 3.3
Martin Panterd21e0b52015-10-10 10:36:22 +0000491 Added ``yield from <expr>`` to delegate control flow to a subiterator.
Nick Coghlan0ed80192012-01-14 14:43:24 +1000492
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500493The parentheses may be omitted when the yield expression is the sole expression
494on the right hand side of an assignment statement.
495
496.. seealso::
497
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300498 :pep:`255` - Simple Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500499 The proposal for adding generators and the :keyword:`yield` statement to Python.
500
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300501 :pep:`342` - Coroutines via Enhanced Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500502 The proposal to enhance the API and syntax of generators, making them
503 usable as simple coroutines.
504
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300505 :pep:`380` - Syntax for Delegating to a Subgenerator
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500506 The proposal to introduce the :token:`yield_from` syntax, making delegation
divyag9778a9102019-05-13 08:05:20 -0500507 to subgenerators easy.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000508
Andrés Delfinobfe18392018-11-07 15:12:12 -0300509 :pep:`525` - Asynchronous Generators
510 The proposal that expanded on :pep:`492` by adding generator capabilities to
511 coroutine functions.
512
Georg Brandl116aa622007-08-15 14:28:22 +0000513.. index:: object: generator
Yury Selivanov66f88282015-06-24 11:04:15 -0400514.. _generator-methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000515
R David Murray2c1d1d62012-08-17 20:48:59 -0400516Generator-iterator methods
517^^^^^^^^^^^^^^^^^^^^^^^^^^
518
519This subsection describes the methods of a generator iterator. They can
520be used to control the execution of a generator function.
521
522Note that calling any of the generator methods below when the generator
523is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000524
525.. index:: exception: StopIteration
526
527
Georg Brandl96593ed2007-09-07 14:15:41 +0000528.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Georg Brandl96593ed2007-09-07 14:15:41 +0000530 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500531 executed yield expression. When a generator function is resumed with a
532 :meth:`~generator.__next__` method, the current yield expression always
533 evaluates to :const:`None`. The execution then continues to the next yield
534 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300535 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500536 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000537 exception is raised.
538
539 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
540 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542
543.. method:: generator.send(value)
544
545 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500546 *value* argument becomes the result of the current yield expression. The
547 :meth:`send` method returns the next value yielded by the generator, or
548 raises :exc:`StopIteration` if the generator exits without yielding another
549 value. When :meth:`send` is called to start the generator, it must be called
550 with :const:`None` as the argument, because there is no yield expression that
551 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000552
553
554.. method:: generator.throw(type[, value[, traceback]])
555
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700556 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000557 and returns the next value yielded by the generator function. If the generator
558 exits without yielding another value, a :exc:`StopIteration` exception is
559 raised. If the generator function does not catch the passed-in exception, or
560 raises a different exception, then that exception propagates to the caller.
561
562.. index:: exception: GeneratorExit
563
564
565.. method:: generator.close()
566
567 Raises a :exc:`GeneratorExit` at the point where the generator function was
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400568 paused. If the generator function then exits gracefully, is already closed,
569 or raises :exc:`GeneratorExit` (by not catching the exception), close
570 returns to its caller. If the generator yields a value, a
571 :exc:`RuntimeError` is raised. If the generator raises any other exception,
572 it is propagated to the caller. :meth:`close` does nothing if the generator
573 has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000574
Chris Jerdonek2654b862012-12-23 15:31:57 -0800575.. index:: single: yield; examples
576
577Examples
578^^^^^^^^
579
Georg Brandl116aa622007-08-15 14:28:22 +0000580Here is a simple example that demonstrates the behavior of generators and
581generator functions::
582
583 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000584 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000585 ... try:
586 ... while True:
587 ... try:
588 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000589 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000590 ... value = e
591 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000592 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000593 ...
594 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000595 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000596 Execution starts when 'next()' is called for the first time.
597 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000598 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000599 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000600 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000601 2
602 >>> generator.throw(TypeError, "spam")
603 TypeError('spam',)
604 >>> generator.close()
605 Don't forget to clean up when 'close()' is called.
606
Chris Jerdonek2654b862012-12-23 15:31:57 -0800607For examples using ``yield from``, see :ref:`pep-380` in "What's New in
608Python."
609
Yury Selivanov03660042016-12-15 17:36:05 -0500610.. _asynchronous-generator-functions:
611
612Asynchronous generator functions
613^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
614
615The presence of a yield expression in a function or method defined using
divyag9778a9102019-05-13 08:05:20 -0500616:keyword:`async def` further defines the function as an
Yury Selivanov03660042016-12-15 17:36:05 -0500617:term:`asynchronous generator` function.
618
619When an asynchronous generator function is called, it returns an
620asynchronous iterator known as an asynchronous generator object.
621That object then controls the execution of the generator function.
622An asynchronous generator object is typically used in an
623:keyword:`async for` statement in a coroutine function analogously to
624how a generator object would be used in a :keyword:`for` statement.
625
626Calling one of the asynchronous generator's methods returns an
627:term:`awaitable` object, and the execution starts when this object
628is awaited on. At that time, the execution proceeds to the first yield
629expression, where it is suspended again, returning the value of
630:token:`expression_list` to the awaiting coroutine. As with a generator,
631suspension means that all local state is retained, including the
632current bindings of local variables, the instruction pointer, the internal
633evaluation stack, and the state of any exception handling. When the execution
634is resumed by awaiting on the next object returned by the asynchronous
635generator's methods, the function can proceed exactly as if the yield
636expression were just another external call. The value of the yield expression
637after resuming depends on the method which resumed the execution. If
638:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
639:meth:`~agen.asend` is used, then the result will be the value passed in to
640that method.
641
642In an asynchronous generator function, yield expressions are allowed anywhere
643in a :keyword:`try` construct. However, if an asynchronous generator is not
644resumed before it is finalized (by reaching a zero reference count or by
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200645being garbage collected), then a yield expression within a :keyword:`!try`
Yury Selivanov03660042016-12-15 17:36:05 -0500646construct could result in a failure to execute pending :keyword:`finally`
647clauses. In this case, it is the responsibility of the event loop or
648scheduler running the asynchronous generator to call the asynchronous
649generator-iterator's :meth:`~agen.aclose` method and run the resulting
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200650coroutine object, thus allowing any pending :keyword:`!finally` clauses
Yury Selivanov03660042016-12-15 17:36:05 -0500651to execute.
652
653To take care of finalization, an event loop should define
654a *finalizer* function which takes an asynchronous generator-iterator
655and presumably calls :meth:`~agen.aclose` and executes the coroutine.
656This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`.
657When first iterated over, an asynchronous generator-iterator will store the
658registered *finalizer* to be called upon finalization. For a reference example
659of a *finalizer* method see the implementation of
660``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`.
661
662The expression ``yield from <expr>`` is a syntax error when used in an
663asynchronous generator function.
664
665.. index:: object: asynchronous-generator
666.. _asynchronous-generator-methods:
667
668Asynchronous generator-iterator methods
669^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
670
671This subsection describes the methods of an asynchronous generator iterator,
672which are used to control the execution of a generator function.
673
674
675.. index:: exception: StopAsyncIteration
676
677.. coroutinemethod:: agen.__anext__()
678
679 Returns an awaitable which when run starts to execute the asynchronous
680 generator or resumes it at the last executed yield expression. When an
divyag9778a9102019-05-13 08:05:20 -0500681 asynchronous generator function is resumed with an :meth:`~agen.__anext__`
Yury Selivanov03660042016-12-15 17:36:05 -0500682 method, the current yield expression always evaluates to :const:`None` in
683 the returned awaitable, which when run will continue to the next yield
684 expression. The value of the :token:`expression_list` of the yield
685 expression is the value of the :exc:`StopIteration` exception raised by
686 the completing coroutine. If the asynchronous generator exits without
divyag9778a9102019-05-13 08:05:20 -0500687 yielding another value, the awaitable instead raises a
Yury Selivanov03660042016-12-15 17:36:05 -0500688 :exc:`StopAsyncIteration` exception, signalling that the asynchronous
689 iteration has completed.
690
691 This method is normally called implicitly by a :keyword:`async for` loop.
692
693
694.. coroutinemethod:: agen.asend(value)
695
696 Returns an awaitable which when run resumes the execution of the
697 asynchronous generator. As with the :meth:`~generator.send()` method for a
698 generator, this "sends" a value into the asynchronous generator function,
699 and the *value* argument becomes the result of the current yield expression.
700 The awaitable returned by the :meth:`asend` method will return the next
701 value yielded by the generator as the value of the raised
702 :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the
703 asynchronous generator exits without yielding another value. When
704 :meth:`asend` is called to start the asynchronous
705 generator, it must be called with :const:`None` as the argument,
706 because there is no yield expression that could receive the value.
707
708
709.. coroutinemethod:: agen.athrow(type[, value[, traceback]])
710
711 Returns an awaitable that raises an exception of type ``type`` at the point
712 where the asynchronous generator was paused, and returns the next value
713 yielded by the generator function as the value of the raised
714 :exc:`StopIteration` exception. If the asynchronous generator exits
divyag9778a9102019-05-13 08:05:20 -0500715 without yielding another value, a :exc:`StopAsyncIteration` exception is
Yury Selivanov03660042016-12-15 17:36:05 -0500716 raised by the awaitable.
717 If the generator function does not catch the passed-in exception, or
delirious-lettuce3378b202017-05-19 14:37:57 -0600718 raises a different exception, then when the awaitable is run that exception
Yury Selivanov03660042016-12-15 17:36:05 -0500719 propagates to the caller of the awaitable.
720
721.. index:: exception: GeneratorExit
722
723
724.. coroutinemethod:: agen.aclose()
725
726 Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
727 the asynchronous generator function at the point where it was paused.
728 If the asynchronous generator function then exits gracefully, is already
729 closed, or raises :exc:`GeneratorExit` (by not catching the exception),
730 then the returned awaitable will raise a :exc:`StopIteration` exception.
731 Any further awaitables returned by subsequent calls to the asynchronous
732 generator will raise a :exc:`StopAsyncIteration` exception. If the
733 asynchronous generator yields a value, a :exc:`RuntimeError` is raised
734 by the awaitable. If the asynchronous generator raises any other exception,
735 it is propagated to the caller of the awaitable. If the asynchronous
736 generator has already exited due to an exception or normal exit, then
737 further calls to :meth:`aclose` will return an awaitable that does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000738
Georg Brandl116aa622007-08-15 14:28:22 +0000739.. _primaries:
740
741Primaries
742=========
743
744.. index:: single: primary
745
746Primaries represent the most tightly bound operations of the language. Their
747syntax is:
748
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700749.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000750 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
751
752
753.. _attribute-references:
754
755Attribute references
756--------------------
757
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300758.. index::
759 pair: attribute; reference
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200760 single: . (dot); attribute reference
Georg Brandl116aa622007-08-15 14:28:22 +0000761
762An attribute reference is a primary followed by a period and a name:
763
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700764.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000765 attributeref: `primary` "." `identifier`
766
767.. index::
768 exception: AttributeError
769 object: module
770 object: list
771
772The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000773references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700774attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500775overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700776the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
777the object produced is determined by the object. Multiple evaluations of the
778same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000779
780
781.. _subscriptions:
782
783Subscriptions
784-------------
785
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300786.. index::
787 single: subscription
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200788 single: [] (square brackets); subscription
Georg Brandl116aa622007-08-15 14:28:22 +0000789
790.. index::
791 object: sequence
792 object: mapping
793 object: string
794 object: tuple
795 object: list
796 object: dictionary
797 pair: sequence; item
798
Miss Skeleton (bot)d05514a2020-10-20 16:58:49 -0700799Subscription of a sequence (string, tuple or list) or mapping (dictionary)
800object usually selects an item from the collection:
Georg Brandl116aa622007-08-15 14:28:22 +0000801
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700802.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000803 subscription: `primary` "[" `expression_list` "]"
804
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700805The primary must evaluate to an object that supports subscription (lists or
806dictionaries for example). User-defined objects can support subscription by
807defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000808
809For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811If the primary is a mapping, the expression list must evaluate to an object
812whose value is one of the keys of the mapping, and the subscription selects the
813value in the mapping that corresponds to that key. (The expression list is a
814tuple except if it has exactly one item.)
815
Andrés Delfino4fddd4e2018-06-15 15:24:25 -0300816If the primary is a sequence, the expression list must evaluate to an integer
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000817or a slice (as discussed in the following section).
818
819The formal syntax makes no special provision for negative indices in
820sequences; however, built-in sequences all provide a :meth:`__getitem__`
821method that interprets negative indices by adding the length of the sequence
822to the index (so that ``x[-1]`` selects the last item of ``x``). The
823resulting value must be a nonnegative integer less than the number of items in
824the sequence, and the subscription selects the item whose index is that value
825(counting from zero). Since the support for negative indices and slicing
826occurs in the object's :meth:`__getitem__` method, subclasses overriding
827this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000828
829.. index::
830 single: character
831 pair: string; item
832
833A string's items are characters. A character is not a separate data type but a
834string of exactly one character.
835
Miss Skeleton (bot)d05514a2020-10-20 16:58:49 -0700836..
837 At the time of writing this, there is no documentation for generic alias
838 or PEP 585. Thus the link currently points to PEP 585 itself.
839 Please change the link for generic alias to reference the correct
840 documentation once documentation for PEP 585 becomes available.
841
842Subscription of certain :term:`classes <class>` or :term:`types <type>`
843creates a `generic alias <https://www.python.org/dev/peps/pep-0585/>`_.
844In this case, user-defined classes can support subscription by providing a
845:meth:`__class_getitem__` classmethod.
846
Georg Brandl116aa622007-08-15 14:28:22 +0000847
848.. _slicings:
849
850Slicings
851--------
852
853.. index::
854 single: slicing
855 single: slice
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200856 single: : (colon); slicing
857 single: , (comma); slicing
Georg Brandl116aa622007-08-15 14:28:22 +0000858
859.. index::
860 object: sequence
861 object: string
862 object: tuple
863 object: list
864
865A slicing selects a range of items in a sequence object (e.g., a string, tuple
866or list). Slicings may be used as expressions or as targets in assignment or
867:keyword:`del` statements. The syntax for a slicing:
868
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700869.. productionlist:: python-grammar
Georg Brandl48310cd2009-01-03 21:18:54 +0000870 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000871 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000872 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000873 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000874 lower_bound: `expression`
875 upper_bound: `expression`
876 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000877
878There is ambiguity in the formal syntax here: anything that looks like an
879expression list also looks like a slice list, so any subscription can be
880interpreted as a slicing. Rather than further complicating the syntax, this is
881disambiguated by defining that in this case the interpretation as a subscription
882takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000883slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000884
885.. index::
886 single: start (slice object attribute)
887 single: stop (slice object attribute)
888 single: step (slice object attribute)
889
Georg Brandla4c8c472014-10-31 10:38:49 +0100890The semantics for a slicing are as follows. The primary is indexed (using the
891same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000892normal subscription) with a key that is constructed from the slice list, as
893follows. If the slice list contains at least one comma, the key is a tuple
894containing the conversion of the slice items; otherwise, the conversion of the
895lone slice item is the key. The conversion of a slice item that is an
896expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300897object (see section :ref:`types`) whose :attr:`~slice.start`,
898:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
899expressions given as lower bound, upper bound and stride, respectively,
900substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000901
902
Chris Jerdonekb4309942012-12-25 14:54:44 -0800903.. index::
904 object: callable
905 single: call
906 single: argument; call semantics
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200907 single: () (parentheses); call
908 single: , (comma); argument list
909 single: = (equals); in function calls
Chris Jerdonekb4309942012-12-25 14:54:44 -0800910
Georg Brandl116aa622007-08-15 14:28:22 +0000911.. _calls:
912
913Calls
914-----
915
Chris Jerdonekb4309942012-12-25 14:54:44 -0800916A call calls a callable object (e.g., a :term:`function`) with a possibly empty
917series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000918
Miss Islington (bot)c0534022020-09-18 00:27:21 -0700919.. productionlist:: python-grammar
Georg Brandldc529c12008-09-21 17:03:29 +0000920 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Martin Panter0c0da482016-06-12 01:46:50 +0000921 argument_list: `positional_arguments` ["," `starred_and_keywords`]
922 : ["," `keywords_arguments`]
923 : | `starred_and_keywords` ["," `keywords_arguments`]
924 : | `keywords_arguments`
Brandt Bucher8bae2192020-03-05 21:19:22 -0800925 positional_arguments: positional_item ("," positional_item)*
926 positional_item: `assignment_expression` | "*" `expression`
Martin Panter0c0da482016-06-12 01:46:50 +0000927 starred_and_keywords: ("*" `expression` | `keyword_item`)
928 : ("," "*" `expression` | "," `keyword_item`)*
929 keywords_arguments: (`keyword_item` | "**" `expression`)
Martin Panter7106a512016-12-24 10:20:38 +0000930 : ("," `keyword_item` | "," "**" `expression`)*
Georg Brandl116aa622007-08-15 14:28:22 +0000931 keyword_item: `identifier` "=" `expression`
932
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700933An optional trailing comma may be present after the positional and keyword arguments
934but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000935
Chris Jerdonekb4309942012-12-25 14:54:44 -0800936.. index::
937 single: parameter; call semantics
938
Georg Brandl116aa622007-08-15 14:28:22 +0000939The primary must evaluate to a callable object (user-defined functions, built-in
940functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000941instances, and all objects having a :meth:`__call__` method are callable). All
942argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800943to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000944
945.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000946
947If keyword arguments are present, they are first converted to positional
948arguments, as follows. First, a list of unfilled slots is created for the
949formal parameters. If there are N positional arguments, they are placed in the
950first N slots. Next, for each keyword argument, the identifier is used to
951determine the corresponding slot (if the identifier is the same as the first
952formal parameter name, the first slot is used, and so on). If the slot is
953already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
954the argument is placed in the slot, filling it (even if the expression is
955``None``, it fills the slot). When all arguments have been processed, the slots
956that are still unfilled are filled with the corresponding default value from the
957function definition. (Default values are calculated, once, when the function is
958defined; thus, a mutable object such as a list or dictionary used as default
959value will be shared by all calls that don't specify an argument value for the
960corresponding slot; this should usually be avoided.) If there are any unfilled
961slots for which no default value is specified, a :exc:`TypeError` exception is
962raised. Otherwise, the list of filled slots is used as the argument list for
963the call.
964
Georg Brandl495f7b52009-10-27 15:28:25 +0000965.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000966
Georg Brandl495f7b52009-10-27 15:28:25 +0000967 An implementation may provide built-in functions whose positional parameters
968 do not have names, even if they are 'named' for the purpose of documentation,
969 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000970 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000971 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000972
Georg Brandl116aa622007-08-15 14:28:22 +0000973If there are more positional arguments than there are formal parameter slots, a
974:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
975``*identifier`` is present; in this case, that formal parameter receives a tuple
976containing the excess positional arguments (or an empty tuple if there were no
977excess positional arguments).
978
979If any keyword argument does not correspond to a formal parameter name, a
980:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
981``**identifier`` is present; in this case, that formal parameter receives a
982dictionary containing the excess keyword arguments (using the keywords as keys
983and the argument values as corresponding values), or a (new) empty dictionary if
984there were no excess keyword arguments.
985
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300986.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200987 single: * (asterisk); in function calls
Martin Panter0c0da482016-06-12 01:46:50 +0000988 single: unpacking; in function calls
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300989
Georg Brandl116aa622007-08-15 14:28:22 +0000990If the syntax ``*expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +0000991evaluate to an :term:`iterable`. Elements from these iterables are
992treated as if they were additional positional arguments. For the call
993``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*,
994this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
995*y1*, ..., *yM*, *x3*, *x4*.
Georg Brandl116aa622007-08-15 14:28:22 +0000996
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000997A consequence of this is that although the ``*expression`` syntax may appear
Martin Panter0c0da482016-06-12 01:46:50 +0000998*after* explicit keyword arguments, it is processed *before* the
999keyword arguments (and any ``**expression`` arguments -- see below). So::
Georg Brandl116aa622007-08-15 14:28:22 +00001000
1001 >>> def f(a, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001002 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +00001003 ...
1004 >>> f(b=1, *(2,))
1005 2 1
1006 >>> f(a=1, *(2,))
1007 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +05301008 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +00001009 TypeError: f() got multiple values for keyword argument 'a'
1010 >>> f(1, *(2,))
1011 1 2
1012
1013It is unusual for both keyword arguments and the ``*expression`` syntax to be
1014used in the same call, so in practice this confusion does not arise.
1015
Eli Bendersky7bd081c2011-07-30 07:05:16 +03001016.. index::
1017 single: **; in function calls
1018
Georg Brandl116aa622007-08-15 14:28:22 +00001019If the syntax ``**expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +00001020evaluate to a :term:`mapping`, the contents of which are treated as
1021additional keyword arguments. If a keyword is already present
1022(as an explicit keyword argument, or from another unpacking),
1023a :exc:`TypeError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001024
1025Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
1026used as positional argument slots or as keyword argument names.
1027
Martin Panter0c0da482016-06-12 01:46:50 +00001028.. versionchanged:: 3.5
1029 Function calls accept any number of ``*`` and ``**`` unpackings,
1030 positional arguments may follow iterable unpackings (``*``),
1031 and keyword arguments may follow dictionary unpackings (``**``).
1032 Originally proposed by :pep:`448`.
1033
Georg Brandl116aa622007-08-15 14:28:22 +00001034A call always returns some value, possibly ``None``, unless it raises an
1035exception. How this value is computed depends on the type of the callable
1036object.
1037
1038If it is---
1039
1040a user-defined function:
1041 .. index::
1042 pair: function; call
1043 triple: user-defined; function; call
1044 object: user-defined function
1045 object: function
1046
1047 The code block for the function is executed, passing it the argument list. The
1048 first thing the code block will do is bind the formal parameters to the
1049 arguments; this is described in section :ref:`function`. When the code block
1050 executes a :keyword:`return` statement, this specifies the return value of the
1051 function call.
1052
1053a built-in function or method:
1054 .. index::
1055 pair: function; call
1056 pair: built-in function; call
1057 pair: method; call
1058 pair: built-in method; call
1059 object: built-in method
1060 object: built-in function
1061 object: method
1062 object: function
1063
1064 The result is up to the interpreter; see :ref:`built-in-funcs` for the
1065 descriptions of built-in functions and methods.
1066
1067a class object:
1068 .. index::
1069 object: class
1070 pair: class object; call
1071
1072 A new instance of that class is returned.
1073
1074a class instance method:
1075 .. index::
1076 object: class instance
1077 object: instance
1078 pair: class instance; call
1079
1080 The corresponding user-defined function is called, with an argument list that is
1081 one longer than the argument list of the call: the instance becomes the first
1082 argument.
1083
1084a class instance:
1085 .. index::
1086 pair: instance; call
1087 single: __call__() (object method)
1088
1089 The class must define a :meth:`__call__` method; the effect is then the same as
1090 if that method was called.
1091
1092
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001093.. index:: keyword: await
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001094.. _await:
1095
1096Await expression
1097================
1098
1099Suspend the execution of :term:`coroutine` on an :term:`awaitable` object.
1100Can only be used inside a :term:`coroutine function`.
1101
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001102.. productionlist:: python-grammar
Serhiy Storchakac7cc9852016-05-08 21:59:46 +03001103 await_expr: "await" `primary`
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001104
1105.. versionadded:: 3.5
1106
1107
Georg Brandl116aa622007-08-15 14:28:22 +00001108.. _power:
1109
1110The power operator
1111==================
1112
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001113.. index::
1114 pair: power; operation
1115 operator: **
1116
Georg Brandl116aa622007-08-15 14:28:22 +00001117The power operator binds more tightly than unary operators on its left; it binds
1118less tightly than unary operators on its right. The syntax is:
1119
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001120.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001121 power: (`await_expr` | `primary`) ["**" `u_expr`]
Georg Brandl116aa622007-08-15 14:28:22 +00001122
1123Thus, in an unparenthesized sequence of power and unary operators, the operators
1124are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +00001125for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001126
1127The power operator has the same semantics as the built-in :func:`pow` function,
1128when called with two arguments: it yields its left argument raised to the power
1129of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +00001130type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +00001131
Georg Brandl96593ed2007-09-07 14:15:41 +00001132For int operands, the result has the same type as the operands unless the second
1133argument is negative; in that case, all arguments are converted to float and a
1134float result is delivered. For example, ``10**2`` returns ``100``, but
1135``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +00001136
1137Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +00001138Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001139number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001140
1141
1142.. _unary:
1143
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001144Unary arithmetic and bitwise operations
1145=======================================
Georg Brandl116aa622007-08-15 14:28:22 +00001146
1147.. index::
1148 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +00001149 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001150
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001151All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +00001152
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001153.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +00001154 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
1155
1156.. index::
1157 single: negation
1158 single: minus
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001159 single: operator; - (minus)
1160 single: - (minus); unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001161
1162The unary ``-`` (minus) operator yields the negation of its numeric argument.
1163
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001164.. index::
1165 single: plus
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001166 single: operator; + (plus)
1167 single: + (plus); unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001168
1169The unary ``+`` (plus) operator yields its numeric argument unchanged.
1170
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001171.. index::
1172 single: inversion
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001173 operator: ~ (tilde)
Christian Heimesfaf2f632008-01-06 16:59:19 +00001174
Georg Brandl95817b32008-05-11 14:30:18 +00001175The unary ``~`` (invert) operator yields the bitwise inversion of its integer
1176argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
1177applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00001178
1179.. index:: exception: TypeError
1180
1181In all three cases, if the argument does not have the proper type, a
1182:exc:`TypeError` exception is raised.
1183
1184
1185.. _binary:
1186
1187Binary arithmetic operations
1188============================
1189
1190.. index:: triple: binary; arithmetic; operation
1191
1192The binary arithmetic operations have the conventional priority levels. Note
1193that some of these operations also apply to certain non-numeric types. Apart
1194from the power operator, there are only two levels, one for multiplicative
1195operators and one for additive operators:
1196
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001197.. productionlist:: python-grammar
Benjamin Petersond51374e2014-04-09 23:55:56 -04001198 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
Andrés Delfinocaccca782018-07-07 17:24:46 -03001199 : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` |
Benjamin Petersond51374e2014-04-09 23:55:56 -04001200 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001201 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
1202
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001203.. index::
1204 single: multiplication
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001205 operator: * (asterisk)
Georg Brandl116aa622007-08-15 14:28:22 +00001206
1207The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +00001208arguments must either both be numbers, or one argument must be an integer and
1209the other must be a sequence. In the former case, the numbers are converted to a
1210common type and then multiplied together. In the latter case, sequence
1211repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001212
Andrés Delfino69511862018-06-15 16:23:00 -03001213.. index::
1214 single: matrix multiplication
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001215 operator: @ (at)
Benjamin Petersond51374e2014-04-09 23:55:56 -04001216
1217The ``@`` (at) operator is intended to be used for matrix multiplication. No
1218builtin Python types implement this operator.
1219
1220.. versionadded:: 3.5
1221
Georg Brandl116aa622007-08-15 14:28:22 +00001222.. index::
1223 exception: ZeroDivisionError
1224 single: division
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001225 operator: / (slash)
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001226 operator: //
Georg Brandl116aa622007-08-15 14:28:22 +00001227
1228The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
1229their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +02001230Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +00001231integer; the result is that of mathematical division with the 'floor' function
1232applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
1233exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001234
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001235.. index::
1236 single: modulo
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001237 operator: % (percent)
Georg Brandl116aa622007-08-15 14:28:22 +00001238
1239The ``%`` (modulo) operator yields the remainder from the division of the first
1240argument by the second. The numeric arguments are first converted to a common
1241type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
1242arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
1243(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
1244result with the same sign as its second operand (or zero); the absolute value of
1245the result is strictly smaller than the absolute value of the second operand
1246[#]_.
1247
Georg Brandl96593ed2007-09-07 14:15:41 +00001248The floor division and modulo operators are connected by the following
1249identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
1250connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
1251x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +00001252
1253In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +00001254also overloaded by string objects to perform old-style string formatting (also
1255known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +00001256Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +00001257
1258The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +00001259function are not defined for complex numbers. Instead, convert to a floating
1260point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +00001261
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001262.. index::
1263 single: addition
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001264 single: operator; + (plus)
1265 single: + (plus); binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001266
Georg Brandl96593ed2007-09-07 14:15:41 +00001267The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001268must either both be numbers or both be sequences of the same type. In the
1269former case, the numbers are converted to a common type and then added together.
1270In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +00001271
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001272.. index::
1273 single: subtraction
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001274 single: operator; - (minus)
1275 single: - (minus); binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001276
1277The ``-`` (subtraction) operator yields the difference of its arguments. The
1278numeric arguments are first converted to a common type.
1279
1280
1281.. _shifting:
1282
1283Shifting operations
1284===================
1285
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001286.. index::
1287 pair: shifting; operation
1288 operator: <<
1289 operator: >>
Georg Brandl116aa622007-08-15 14:28:22 +00001290
1291The shifting operations have lower priority than the arithmetic operations:
1292
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001293.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001294 shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001295
Georg Brandl96593ed2007-09-07 14:15:41 +00001296These operators accept integers as arguments. They shift the first argument to
1297the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001298
1299.. index:: exception: ValueError
1300
Georg Brandl0aaae262013-10-08 21:47:18 +02001301A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
1302shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001303
1304
1305.. _bitwise:
1306
Christian Heimesfaf2f632008-01-06 16:59:19 +00001307Binary bitwise operations
1308=========================
Georg Brandl116aa622007-08-15 14:28:22 +00001309
Christian Heimesfaf2f632008-01-06 16:59:19 +00001310.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001311
1312Each of the three bitwise operations has a different priority level:
1313
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001314.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +00001315 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1316 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1317 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1318
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001319.. index::
1320 pair: bitwise; and
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001321 operator: & (ampersand)
Georg Brandl116aa622007-08-15 14:28:22 +00001322
Georg Brandl96593ed2007-09-07 14:15:41 +00001323The ``&`` operator yields the bitwise AND of its arguments, which must be
1324integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001325
1326.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001327 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001328 pair: exclusive; or
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001329 operator: ^ (caret)
Georg Brandl116aa622007-08-15 14:28:22 +00001330
1331The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001332must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001333
1334.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001335 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001336 pair: inclusive; or
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001337 operator: | (vertical bar)
Georg Brandl116aa622007-08-15 14:28:22 +00001338
1339The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001340must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001341
1342
1343.. _comparisons:
1344
1345Comparisons
1346===========
1347
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001348.. index::
1349 single: comparison
1350 pair: C; language
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001351 operator: < (less)
1352 operator: > (greater)
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001353 operator: <=
1354 operator: >=
1355 operator: ==
1356 operator: !=
Georg Brandl116aa622007-08-15 14:28:22 +00001357
1358Unlike C, all comparison operations in Python have the same priority, which is
1359lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1360C, expressions like ``a < b < c`` have the interpretation that is conventional
1361in mathematics:
1362
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001363.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001364 comparison: `or_expr` (`comp_operator` `or_expr`)*
Georg Brandl116aa622007-08-15 14:28:22 +00001365 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1366 : | "is" ["not"] | ["not"] "in"
1367
1368Comparisons yield boolean values: ``True`` or ``False``.
1369
1370.. index:: pair: chaining; comparisons
1371
1372Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1373``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1374cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1375
Guido van Rossum04110fb2007-08-24 16:32:05 +00001376Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1377*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1378to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1379evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001380
Guido van Rossum04110fb2007-08-24 16:32:05 +00001381Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001382*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1383pretty).
1384
Martin Panteraa0da862015-09-23 05:28:13 +00001385Value comparisons
1386-----------------
1387
Georg Brandl116aa622007-08-15 14:28:22 +00001388The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
Martin Panteraa0da862015-09-23 05:28:13 +00001389values of two objects. The objects do not need to have the same type.
Georg Brandl116aa622007-08-15 14:28:22 +00001390
Martin Panteraa0da862015-09-23 05:28:13 +00001391Chapter :ref:`objects` states that objects have a value (in addition to type
1392and identity). The value of an object is a rather abstract notion in Python:
1393For example, there is no canonical access method for an object's value. Also,
1394there is no requirement that the value of an object should be constructed in a
1395particular way, e.g. comprised of all its data attributes. Comparison operators
1396implement a particular notion of what the value of an object is. One can think
1397of them as defining the value of an object indirectly, by means of their
1398comparison implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00001399
Martin Panteraa0da862015-09-23 05:28:13 +00001400Because all types are (direct or indirect) subtypes of :class:`object`, they
1401inherit the default comparison behavior from :class:`object`. Types can
1402customize their comparison behavior by implementing
1403:dfn:`rich comparison methods` like :meth:`__lt__`, described in
1404:ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001405
Martin Panteraa0da862015-09-23 05:28:13 +00001406The default behavior for equality comparison (``==`` and ``!=``) is based on
1407the identity of the objects. Hence, equality comparison of instances with the
1408same identity results in equality, and equality comparison of instances with
1409different identities results in inequality. A motivation for this default
1410behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1411implies ``x == y``).
1412
1413A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1414an attempt raises :exc:`TypeError`. A motivation for this default behavior is
1415the lack of a similar invariant as for equality.
1416
1417The behavior of the default equality comparison, that instances with different
1418identities are always unequal, may be in contrast to what types will need that
1419have a sensible definition of object value and value-based equality. Such
1420types will need to customize their comparison behavior, and in fact, a number
1421of built-in types have done that.
1422
1423The following list describes the comparison behavior of the most important
1424built-in types.
1425
1426* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1427 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
1428 compared within and across their types, with the restriction that complex
1429 numbers do not support order comparison. Within the limits of the types
1430 involved, they compare mathematically (algorithmically) correct without loss
1431 of precision.
1432
Tony Fluryad8a0002018-09-14 18:48:50 +01001433 The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are
1434 special. Any ordered comparison of a number to a not-a-number value is false.
1435 A counter-intuitive implication is that not-a-number values are not equal to
Mark Dickinson810f68f2020-04-05 10:25:24 +01001436 themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3`` and
1437 ``x == x`` are all false, while ``x != x`` is true. This behavior is
1438 compliant with IEEE 754.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001439
Raymond Hettingeredd21122019-08-24 10:43:55 -07001440* ``None`` and ``NotImplemented`` are singletons. :PEP:`8` advises that
1441 comparisons for singletons should always be done with ``is`` or ``is not``,
1442 never the equality operators.
1443
Martin Panteraa0da862015-09-23 05:28:13 +00001444* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
1445 compared within and across their types. They compare lexicographically using
1446 the numeric values of their elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001447
Martin Panteraa0da862015-09-23 05:28:13 +00001448* Strings (instances of :class:`str`) compare lexicographically using the
1449 numerical Unicode code points (the result of the built-in function
1450 :func:`ord`) of their characters. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001451
Martin Panteraa0da862015-09-23 05:28:13 +00001452 Strings and binary sequences cannot be directly compared.
Georg Brandl116aa622007-08-15 14:28:22 +00001453
Martin Panteraa0da862015-09-23 05:28:13 +00001454* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can
1455 be compared only within each of their types, with the restriction that ranges
1456 do not support order comparison. Equality comparison across these types
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +02001457 results in inequality, and ordering comparison across these types raises
Martin Panteraa0da862015-09-23 05:28:13 +00001458 :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001459
Martin Panteraa0da862015-09-23 05:28:13 +00001460 Sequences compare lexicographically using comparison of corresponding
Raymond Hettingeredd21122019-08-24 10:43:55 -07001461 elements. The built-in containers typically assume identical objects are
1462 equal to themselves. That lets them bypass equality tests for identical
1463 objects to improve performance and to maintain their internal invariants.
Martin Panteraa0da862015-09-23 05:28:13 +00001464
1465 Lexicographical comparison between built-in collections works as follows:
1466
1467 - For two collections to compare equal, they must be of the same type, have
1468 the same length, and each pair of corresponding elements must compare
1469 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1470 same).
1471
1472 - Collections that support order comparison are ordered the same as their
1473 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same
1474 value as ``x <= y``). If a corresponding element does not exist, the
1475 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1476 true).
1477
1478* Mappings (instances of :class:`dict`) compare equal if and only if they have
cocoatomocdcac032017-03-31 14:48:49 +09001479 equal `(key, value)` pairs. Equality comparison of the keys and values
Martin Panteraa0da862015-09-23 05:28:13 +00001480 enforces reflexivity.
1481
1482 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
1483
1484* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within
1485 and across their types.
1486
1487 They define order
1488 comparison operators to mean subset and superset tests. Those relations do
1489 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}``
1490 are not equal, nor subsets of one another, nor supersets of one
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001491 another). Accordingly, sets are not appropriate arguments for functions
Martin Panteraa0da862015-09-23 05:28:13 +00001492 which depend on total ordering (for example, :func:`min`, :func:`max`, and
1493 :func:`sorted` produce undefined results given a list of sets as inputs).
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001494
Martin Panteraa0da862015-09-23 05:28:13 +00001495 Comparison of sets enforces reflexivity of its elements.
Georg Brandl116aa622007-08-15 14:28:22 +00001496
Martin Panteraa0da862015-09-23 05:28:13 +00001497* Most other built-in types have no comparison methods implemented, so they
1498 inherit the default comparison behavior.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001499
Martin Panteraa0da862015-09-23 05:28:13 +00001500User-defined classes that customize their comparison behavior should follow
1501some consistency rules, if possible:
1502
1503* Equality comparison should be reflexive.
1504 In other words, identical objects should compare equal:
1505
1506 ``x is y`` implies ``x == y``
1507
1508* Comparison should be symmetric.
1509 In other words, the following expressions should have the same result:
1510
1511 ``x == y`` and ``y == x``
1512
1513 ``x != y`` and ``y != x``
1514
1515 ``x < y`` and ``y > x``
1516
1517 ``x <= y`` and ``y >= x``
1518
1519* Comparison should be transitive.
1520 The following (non-exhaustive) examples illustrate that:
1521
1522 ``x > y and y > z`` implies ``x > z``
1523
1524 ``x < y and y <= z`` implies ``x < z``
1525
1526* Inverse comparison should result in the boolean negation.
1527 In other words, the following expressions should have the same result:
1528
1529 ``x == y`` and ``not x != y``
1530
1531 ``x < y`` and ``not x >= y`` (for total ordering)
1532
1533 ``x > y`` and ``not x <= y`` (for total ordering)
1534
1535 The last two expressions apply to totally ordered collections (e.g. to
1536 sequences, but not to sets or mappings). See also the
1537 :func:`~functools.total_ordering` decorator.
1538
Martin Panter8dbb0ca2017-01-29 10:00:23 +00001539* The :func:`hash` result should be consistent with equality.
1540 Objects that are equal should either have the same hash value,
1541 or be marked as unhashable.
1542
Martin Panteraa0da862015-09-23 05:28:13 +00001543Python does not enforce these consistency rules. In fact, the not-a-number
1544values are an example for not following these rules.
1545
1546
1547.. _in:
1548.. _not in:
Georg Brandl495f7b52009-10-27 15:28:25 +00001549.. _membership-test-details:
1550
Martin Panteraa0da862015-09-23 05:28:13 +00001551Membership test operations
1552--------------------------
1553
Georg Brandl96593ed2007-09-07 14:15:41 +00001554The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301555s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
1556``x not in s`` returns the negation of ``x in s``. All built-in sequences and
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001557set types support this as well as dictionary, for which :keyword:`!in` tests
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301558whether the dictionary has a given key. For container types such as list, tuple,
1559set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001560to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001561
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301562For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
Georg Brandl4b491312007-08-31 09:22:56 +00001563substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1564always considered to be a substring of any other string, so ``"" in "abc"`` will
1565return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001566
Georg Brandl116aa622007-08-15 14:28:22 +00001567For user-defined classes which define the :meth:`__contains__` method, ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301568y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and
1569``False`` otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001570
Georg Brandl495f7b52009-10-27 15:28:25 +00001571For user-defined classes which do not define :meth:`__contains__` but do define
Antti Haapala2f5b9dc2019-05-30 23:19:29 +03001572:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z``, for which the
1573expression ``x is z or x == z`` is true, is produced while iterating over ``y``.
1574If an exception is raised during the iteration, it is as if :keyword:`in` raised
1575that exception.
Georg Brandl495f7b52009-10-27 15:28:25 +00001576
1577Lastly, the old-style iteration protocol is tried: if a class defines
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301578:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
Antti Haapala2f5b9dc2019-05-30 23:19:29 +03001579integer index *i* such that ``x is y[i] or x == y[i]``, and no lower integer index
1580raises the :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001581if :keyword:`in` raised that exception).
1582
1583.. index::
1584 operator: in
1585 operator: not in
1586 pair: membership; test
1587 object: sequence
1588
divyag9778a9102019-05-13 08:05:20 -05001589The operator :keyword:`not in` is defined to have the inverse truth value of
Georg Brandl116aa622007-08-15 14:28:22 +00001590:keyword:`in`.
1591
1592.. index::
1593 operator: is
1594 operator: is not
1595 pair: identity; test
1596
Martin Panteraa0da862015-09-23 05:28:13 +00001597
1598.. _is:
1599.. _is not:
1600
1601Identity comparisons
1602--------------------
1603
divyag9778a9102019-05-13 08:05:20 -05001604The operators :keyword:`is` and :keyword:`is not` test for an object's identity: ``x
1605is y`` is true if and only if *x* and *y* are the same object. An Object's identity
Raymond Hettinger06e18a72016-09-11 17:23:49 -07001606is determined using the :meth:`id` function. ``x is not y`` yields the inverse
1607truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001608
1609
1610.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001611.. _and:
1612.. _or:
1613.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001614
1615Boolean operations
1616==================
1617
1618.. index::
1619 pair: Conditional; expression
1620 pair: Boolean; operation
1621
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001622.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +00001623 or_test: `and_test` | `or_test` "or" `and_test`
1624 and_test: `not_test` | `and_test` "and" `not_test`
1625 not_test: `comparison` | "not" `not_test`
1626
1627In the context of Boolean operations, and also when expressions are used by
1628control flow statements, the following values are interpreted as false:
1629``False``, ``None``, numeric zero of all types, and empty strings and containers
1630(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001631other values are interpreted as true. User-defined objects can customize their
1632truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001633
1634.. index:: operator: not
1635
1636The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1637otherwise.
1638
Georg Brandl116aa622007-08-15 14:28:22 +00001639.. index:: operator: and
1640
1641The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1642returned; otherwise, *y* is evaluated and the resulting value is returned.
1643
1644.. index:: operator: or
1645
1646The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1647returned; otherwise, *y* is evaluated and the resulting value is returned.
1648
Andre Delfino55f41e42018-12-05 16:45:30 -03001649Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
Georg Brandl116aa622007-08-15 14:28:22 +00001650they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001651argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001652replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001653the desired value. Because :keyword:`not` has to create a new value, it
1654returns a boolean value regardless of the type of its argument
1655(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001656
1657
Brandt Bucher8bae2192020-03-05 21:19:22 -08001658Assignment expressions
1659======================
1660
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001661.. productionlist:: python-grammar
Brandt Bucher8bae2192020-03-05 21:19:22 -08001662 assignment_expression: [`identifier` ":="] `expression`
1663
Miss Islington (bot)616734b2020-07-25 16:40:48 -07001664An assignment expression (sometimes also called a "named expression" or
1665"walrus") assigns an :token:`expression` to an :token:`identifier`, while also
1666returning the value of the :token:`expression`.
Brandt Bucher8bae2192020-03-05 21:19:22 -08001667
Miss Islington (bot)616734b2020-07-25 16:40:48 -07001668One common use case is when handling matched regular expressions:
1669
1670.. code-block:: python
1671
1672 if matching := pattern.search(data):
1673 do_something(matching)
1674
1675Or, when processing a file stream in chunks:
1676
1677.. code-block:: python
1678
1679 while chunk := file.read(9000):
1680 process(chunk)
1681
1682.. versionadded:: 3.8
1683 See :pep:`572` for more details about assignment expressions.
Brandt Bucher8bae2192020-03-05 21:19:22 -08001684
1685
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001686.. _if_expr:
1687
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001688Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001689=======================
1690
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001691.. index::
1692 pair: conditional; expression
1693 pair: ternary; operator
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001694 single: if; conditional expression
1695 single: else; conditional expression
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001696
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001697.. productionlist:: python-grammar
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001698 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001699 expression: `conditional_expression` | `lambda_expr`
1700 expression_nocond: `or_test` | `lambda_expr_nocond`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001701
1702Conditional expressions (sometimes called a "ternary operator") have the lowest
1703priority of all Python operations.
1704
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001705The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1706If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001707evaluated and its value is returned.
1708
1709See :pep:`308` for more details about conditional expressions.
1710
1711
Georg Brandl116aa622007-08-15 14:28:22 +00001712.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001713.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001714
1715Lambdas
1716=======
1717
1718.. index::
1719 pair: lambda; expression
1720 pair: lambda; form
1721 pair: anonymous; function
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001722 single: : (colon); lambda expression
Georg Brandl116aa622007-08-15 14:28:22 +00001723
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001724.. productionlist:: python-grammar
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001725 lambda_expr: "lambda" [`parameter_list`] ":" `expression`
1726 lambda_expr_nocond: "lambda" [`parameter_list`] ":" `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001727
Zachary Ware2f78b842014-06-03 09:32:40 -05001728Lambda expressions (sometimes called lambda forms) are used to create anonymous
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001729functions. The expression ``lambda parameters: expression`` yields a function
Martin Panter1050d2d2016-07-26 11:18:21 +02001730object. The unnamed object behaves like a function object defined with:
1731
1732.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +00001733
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001734 def <lambda>(parameters):
Georg Brandl116aa622007-08-15 14:28:22 +00001735 return expression
1736
1737See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001738functions created with lambda expressions cannot contain statements or
1739annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001740
Georg Brandl116aa622007-08-15 14:28:22 +00001741
1742.. _exprlists:
1743
1744Expression lists
1745================
1746
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001747.. index::
1748 pair: expression; list
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001749 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +00001750
Miss Islington (bot)c0534022020-09-18 00:27:21 -07001751.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001752 expression_list: `expression` ("," `expression`)* [","]
1753 starred_list: `starred_item` ("," `starred_item`)* [","]
1754 starred_expression: `expression` | (`starred_item` ",")* [`starred_item`]
Brandt Bucher8bae2192020-03-05 21:19:22 -08001755 starred_item: `assignment_expression` | "*" `or_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001756
1757.. index:: object: tuple
1758
Martin Panter0c0da482016-06-12 01:46:50 +00001759Except when part of a list or set display, an expression list
1760containing at least one comma yields a tuple. The length of
Georg Brandl116aa622007-08-15 14:28:22 +00001761the tuple is the number of expressions in the list. The expressions are
1762evaluated from left to right.
1763
Martin Panter0c0da482016-06-12 01:46:50 +00001764.. index::
1765 pair: iterable; unpacking
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001766 single: * (asterisk); in expression lists
Martin Panter0c0da482016-06-12 01:46:50 +00001767
1768An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be
1769an :term:`iterable`. The iterable is expanded into a sequence of items,
1770which are included in the new tuple, list, or set, at the site of
1771the unpacking.
1772
1773.. versionadded:: 3.5
1774 Iterable unpacking in expression lists, originally proposed by :pep:`448`.
1775
Georg Brandl116aa622007-08-15 14:28:22 +00001776.. index:: pair: trailing; comma
1777
1778The trailing comma is required only to create a single tuple (a.k.a. a
1779*singleton*); it is optional in all other cases. A single expression without a
1780trailing comma doesn't create a tuple, but rather yields the value of that
1781expression. (To create an empty tuple, use an empty pair of parentheses:
1782``()``.)
1783
1784
1785.. _evalorder:
1786
1787Evaluation order
1788================
1789
1790.. index:: pair: evaluation; order
1791
Georg Brandl96593ed2007-09-07 14:15:41 +00001792Python evaluates expressions from left to right. Notice that while evaluating
1793an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001794
1795In the following lines, expressions will be evaluated in the arithmetic order of
1796their suffixes::
1797
1798 expr1, expr2, expr3, expr4
1799 (expr1, expr2, expr3, expr4)
1800 {expr1: expr2, expr3: expr4}
1801 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001802 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001803 expr3, expr4 = expr1, expr2
1804
1805
1806.. _operator-summary:
1807
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001808Operator precedence
1809===================
Georg Brandl116aa622007-08-15 14:28:22 +00001810
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001811.. index::
1812 pair: operator; precedence
Georg Brandl116aa622007-08-15 14:28:22 +00001813
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001814The following table summarizes the operator precedence in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001815precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001816the same box have the same precedence. Unless the syntax is explicitly given,
1817operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001818exponentiation, which groups from right to left).
1819
1820Note that comparisons, membership tests, and identity tests, all have the same
1821precedence and have a left-to-right chaining feature as described in the
1822:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001823
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001824
1825+-----------------------------------------------+-------------------------------------+
1826| Operator | Description |
1827+===============================================+=====================================+
Emily Morehouse6357c952019-09-11 15:37:12 +01001828| ``:=`` | Assignment expression |
1829+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001830| :keyword:`lambda` | Lambda expression |
1831+-----------------------------------------------+-------------------------------------+
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001832| :keyword:`if <if_expr>` -- :keyword:`!else` | Conditional expression |
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001833+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001834| :keyword:`or` | Boolean OR |
1835+-----------------------------------------------+-------------------------------------+
1836| :keyword:`and` | Boolean AND |
1837+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001838| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001839+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001840| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001841| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001842| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001843+-----------------------------------------------+-------------------------------------+
1844| ``|`` | Bitwise OR |
1845+-----------------------------------------------+-------------------------------------+
1846| ``^`` | Bitwise XOR |
1847+-----------------------------------------------+-------------------------------------+
1848| ``&`` | Bitwise AND |
1849+-----------------------------------------------+-------------------------------------+
1850| ``<<``, ``>>`` | Shifts |
1851+-----------------------------------------------+-------------------------------------+
1852| ``+``, ``-`` | Addition and subtraction |
1853+-----------------------------------------------+-------------------------------------+
Benjamin Petersond51374e2014-04-09 23:55:56 -04001854| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
svelankar9b47af62017-09-17 20:56:16 -04001855| | multiplication, division, floor |
1856| | division, remainder [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001857+-----------------------------------------------+-------------------------------------+
1858| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1859+-----------------------------------------------+-------------------------------------+
1860| ``**`` | Exponentiation [#]_ |
1861+-----------------------------------------------+-------------------------------------+
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001862| :keyword:`await` ``x`` | Await expression |
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001863+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001864| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1865| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1866+-----------------------------------------------+-------------------------------------+
Andre Delfinodc269972019-09-11 10:16:11 -03001867| ``(expressions...)``, | Binding or parenthesized |
1868| | expression, |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001869| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001870| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001871| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001872+-----------------------------------------------+-------------------------------------+
1873
Georg Brandl116aa622007-08-15 14:28:22 +00001874
1875.. rubric:: Footnotes
1876
Georg Brandl116aa622007-08-15 14:28:22 +00001877.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1878 true numerically due to roundoff. For example, and assuming a platform on which
1879 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1880 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001881 1e100``, which is numerically exactly equal to ``1e100``. The function
1882 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001883 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1884 is more appropriate depends on the application.
1885
1886.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001887 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001888 cases, Python returns the latter result, in order to preserve that
1889 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1890
Martin Panteraa0da862015-09-23 05:28:13 +00001891.. [#] The Unicode standard distinguishes between :dfn:`code points`
1892 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
1893 While most abstract characters in Unicode are only represented using one
1894 code point, there is a number of abstract characters that can in addition be
1895 represented using a sequence of more than one code point. For example, the
1896 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
1897 as a single :dfn:`precomposed character` at code position U+00C7, or as a
1898 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
1899 LETTER C), followed by a :dfn:`combining character` at code position U+0327
1900 (COMBINING CEDILLA).
1901
1902 The comparison operators on strings compare at the level of Unicode code
1903 points. This may be counter-intuitive to humans. For example,
1904 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1905 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".
1906
1907 To compare strings at the level of abstract characters (that is, in a way
1908 intuitive to humans), use :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001909
Georg Brandl48310cd2009-01-03 21:18:54 +00001910.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001911 descriptors, you may notice seemingly unusual behaviour in certain uses of
1912 the :keyword:`is` operator, like those involving comparisons between instance
1913 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001914
Georg Brandl063f2372010-12-01 15:32:43 +00001915.. [#] The ``%`` operator is also used for string formatting; the same
1916 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001917
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001918.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1919 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.