blob: 8ac626444843d20149873fb410835832c07ebd7d [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
Victor Stinner8af239e2020-09-18 09:10:15 +020016.. 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
Victor Stinner8af239e2020-09-18 09:10:15 +020057.. 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
Victor Stinner8af239e2020-09-18 09:10:15 +0200106.. 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
Victor Stinner8af239e2020-09-18 09:10:15 +0200137.. 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
Florian Dahlitz2d55aa92020-10-20 23:27:07 +0200165.. index:: single: comprehensions
166
Georg Brandl96593ed2007-09-07 14:15:41 +0000167For constructing a list, a set or a dictionary Python provides special syntax
168called "displays", each of them in two flavors:
169
170* either the container contents are listed explicitly, or
171
172* they are computed via a set of looping and filtering instructions, called a
173 :dfn:`comprehension`.
174
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300175.. index::
176 single: for; in comprehensions
177 single: if; in comprehensions
178 single: async for; in comprehensions
179
Georg Brandl96593ed2007-09-07 14:15:41 +0000180Common syntax elements for comprehensions are:
181
Victor Stinner8af239e2020-09-18 09:10:15 +0200182.. productionlist:: python-grammar
Brandt Bucher8bae2192020-03-05 21:19:22 -0800183 comprehension: `assignment_expression` `comp_for`
Serhiy Storchakad08972f2018-04-11 19:15:51 +0300184 comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`]
Georg Brandl96593ed2007-09-07 14:15:41 +0000185 comp_iter: `comp_for` | `comp_if`
186 comp_if: "if" `expression_nocond` [`comp_iter`]
187
188The comprehension consists of a single expression followed by at least one
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200189:keyword:`!for` clause and zero or more :keyword:`!for` or :keyword:`!if` clauses.
Georg Brandl96593ed2007-09-07 14:15:41 +0000190In this case, the elements of the new container are those that would be produced
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200191by considering each of the :keyword:`!for` or :keyword:`!if` clauses a block,
Georg Brandl96593ed2007-09-07 14:15:41 +0000192nesting from left to right, and evaluating the expression to produce an element
193each time the innermost block is reached.
194
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200195However, aside from the iterable expression in the leftmost :keyword:`!for` clause,
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200196the comprehension is executed in a separate implicitly nested scope. This ensures
197that names assigned to in the target list don't "leak" into the enclosing scope.
198
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200199The iterable expression in the leftmost :keyword:`!for` clause is evaluated
Johnny Gérard4ef9b8e2019-05-13 05:39:32 +0200200directly in the enclosing scope and then passed as an argument to the implicitly
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200201nested scope. Subsequent :keyword:`!for` clauses and any filter condition in the
202leftmost :keyword:`!for` clause cannot be evaluated in the enclosing scope as
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200203they may depend on the values obtained from the leftmost iterable. For example:
204``[x*y for x in range(10) for y in range(x, x+10)]``.
205
206To ensure the comprehension always results in a container of the appropriate
207type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200208nested scope.
Georg Brandl02c30562007-09-07 17:52:53 +0000209
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300210.. index::
211 single: await; in comprehensions
212
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200213Since Python 3.6, in an :keyword:`async def` function, an :keyword:`!async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500214clause may be used to iterate over a :term:`asynchronous iterator`.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200215A comprehension in an :keyword:`!async def` function may consist of either a
216:keyword:`!for` or :keyword:`!async for` clause following the leading
217expression, may contain additional :keyword:`!for` or :keyword:`!async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500218clauses, and may also use :keyword:`await` expressions.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200219If a comprehension contains either :keyword:`!async for` clauses
220or :keyword:`!await` expressions it is called an
Yury Selivanov03660042016-12-15 17:36:05 -0500221:dfn:`asynchronous comprehension`. An asynchronous comprehension may
222suspend the execution of the coroutine function in which it appears.
223See also :pep:`530`.
Georg Brandl96593ed2007-09-07 14:15:41 +0000224
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200225.. versionadded:: 3.6
226 Asynchronous comprehensions were introduced.
227
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200228.. versionchanged:: 3.8
229 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200230
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232.. _lists:
233
234List displays
235-------------
236
237.. index::
238 pair: list; display
239 pair: list; comprehensions
Georg Brandl96593ed2007-09-07 14:15:41 +0000240 pair: empty; list
241 object: list
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200242 single: [] (square brackets); list expression
243 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245A list display is a possibly empty series of expressions enclosed in square
246brackets:
247
Victor Stinner8af239e2020-09-18 09:10:15 +0200248.. productionlist:: python-grammar
Martin Panter0c0da482016-06-12 01:46:50 +0000249 list_display: "[" [`starred_list` | `comprehension`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000250
Georg Brandl96593ed2007-09-07 14:15:41 +0000251A list display yields a new list object, the contents being specified by either
252a list of expressions or a comprehension. When a comma-separated list of
253expressions is supplied, its elements are evaluated from left to right and
254placed into the list object in that order. When a comprehension is supplied,
255the list is constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257
Georg Brandl96593ed2007-09-07 14:15:41 +0000258.. _set:
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Georg Brandl96593ed2007-09-07 14:15:41 +0000260Set displays
261------------
Georg Brandl116aa622007-08-15 14:28:22 +0000262
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300263.. index::
264 pair: set; display
Florian Dahlitz2d55aa92020-10-20 23:27:07 +0200265 pair: set; comprehensions
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300266 object: set
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200267 single: {} (curly brackets); set expression
268 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Georg Brandl96593ed2007-09-07 14:15:41 +0000270A set display is denoted by curly braces and distinguishable from dictionary
271displays by the lack of colons separating keys and values:
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Victor Stinner8af239e2020-09-18 09:10:15 +0200273.. productionlist:: python-grammar
Martin Panter0c0da482016-06-12 01:46:50 +0000274 set_display: "{" (`starred_list` | `comprehension`) "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000275
Georg Brandl96593ed2007-09-07 14:15:41 +0000276A set display yields a new mutable set object, the contents being specified by
277either a sequence of expressions or a comprehension. When a comma-separated
278list of expressions is supplied, its elements are evaluated from left to right
279and added to the set object. When a comprehension is supplied, the set is
280constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
Georg Brandl528cdb12008-09-21 07:09:51 +0000282An empty set cannot be constructed with ``{}``; this literal constructs an empty
283dictionary.
Christian Heimes78644762008-03-04 23:39:23 +0000284
285
Georg Brandl116aa622007-08-15 14:28:22 +0000286.. _dict:
287
288Dictionary displays
289-------------------
290
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300291.. index::
292 pair: dictionary; display
Florian Dahlitz2d55aa92020-10-20 23:27:07 +0200293 pair: dictionary; comprehensions
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300294 key, datum, key/datum pair
295 object: dictionary
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200296 single: {} (curly brackets); dictionary expression
297 single: : (colon); in dictionary expressions
298 single: , (comma); in dictionary displays
Georg Brandl116aa622007-08-15 14:28:22 +0000299
300A dictionary display is a possibly empty series of key/datum pairs enclosed in
301curly braces:
302
Victor Stinner8af239e2020-09-18 09:10:15 +0200303.. productionlist:: python-grammar
Georg Brandl96593ed2007-09-07 14:15:41 +0000304 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000305 key_datum_list: `key_datum` ("," `key_datum`)* [","]
Martin Panter0c0da482016-06-12 01:46:50 +0000306 key_datum: `expression` ":" `expression` | "**" `or_expr`
Georg Brandl96593ed2007-09-07 14:15:41 +0000307 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309A dictionary display yields a new dictionary object.
310
Georg Brandl96593ed2007-09-07 14:15:41 +0000311If a comma-separated sequence of key/datum pairs is given, they are evaluated
312from left to right to define the entries of the dictionary: each key object is
313used as a key into the dictionary to store the corresponding datum. This means
314that you can specify the same key multiple times in the key/datum list, and the
315final dictionary's value for that key will be the last one given.
316
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300317.. index::
318 unpacking; dictionary
319 single: **; in dictionary displays
Martin Panter0c0da482016-06-12 01:46:50 +0000320
321A double asterisk ``**`` denotes :dfn:`dictionary unpacking`.
322Its operand must be a :term:`mapping`. Each mapping item is added
323to the new dictionary. Later values replace values already set by
324earlier key/datum pairs and earlier dictionary unpackings.
325
326.. versionadded:: 3.5
327 Unpacking into dictionary displays, originally proposed by :pep:`448`.
328
Georg Brandl96593ed2007-09-07 14:15:41 +0000329A dict comprehension, in contrast to list and set comprehensions, needs two
330expressions separated with a colon followed by the usual "for" and "if" clauses.
331When the comprehension is run, the resulting key and value elements are inserted
332in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000335 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000338:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000339all mutable objects.) Clashes between duplicate keys are not detected; the last
340datum (textually rightmost in the display) stored for a given key value
341prevails.
342
Jörn Heisslerc8a35412019-06-22 16:40:55 +0200343.. versionchanged:: 3.8
344 Prior to Python 3.8, in dict comprehensions, the evaluation order of key
345 and value was not well-defined. In CPython, the value was evaluated before
346 the key. Starting with 3.8, the key is evaluated before the value, as
347 proposed by :pep:`572`.
348
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Georg Brandl96593ed2007-09-07 14:15:41 +0000350.. _genexpr:
351
352Generator expressions
353---------------------
354
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300355.. index::
356 pair: generator; expression
357 object: generator
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200358 single: () (parentheses); generator expression
Georg Brandl96593ed2007-09-07 14:15:41 +0000359
360A generator expression is a compact generator notation in parentheses:
361
Victor Stinner8af239e2020-09-18 09:10:15 +0200362.. productionlist:: python-grammar
Georg Brandl96593ed2007-09-07 14:15:41 +0000363 generator_expression: "(" `expression` `comp_for` ")"
364
365A generator expression yields a new generator object. Its syntax is the same as
366for comprehensions, except that it is enclosed in parentheses instead of
367brackets or curly braces.
368
369Variables used in the generator expression are evaluated lazily when the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700370:meth:`~generator.__next__` method is called for the generator object (in the same
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200371fashion as normal generators). However, the iterable expression in the
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200372leftmost :keyword:`!for` clause is immediately evaluated, so that an error
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200373produced by it will be emitted at the point where the generator expression
374is defined, rather than at the point where the first value is retrieved.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200375Subsequent :keyword:`!for` clauses and any filter condition in the leftmost
376:keyword:`!for` clause cannot be evaluated in the enclosing scope as they may
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200377depend on the values obtained from the leftmost iterable. For example:
378``(x*y for x in range(10) for y in range(x, x+10))``.
Georg Brandl96593ed2007-09-07 14:15:41 +0000379
380The parentheses can be omitted on calls with only one argument. See section
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700381:ref:`calls` for details.
Georg Brandl96593ed2007-09-07 14:15:41 +0000382
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200383To avoid interfering with the expected operation of the generator expression
384itself, ``yield`` and ``yield from`` expressions are prohibited in the
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200385implicitly defined generator.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200386
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200387If a generator expression contains either :keyword:`!async for`
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400388clauses or :keyword:`await` expressions it is called an
389:dfn:`asynchronous generator expression`. An asynchronous generator
390expression returns a new asynchronous generator object,
391which is an asynchronous iterator (see :ref:`async-iterators`).
392
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200393.. versionadded:: 3.6
394 Asynchronous generator expressions were introduced.
395
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400396.. versionchanged:: 3.7
397 Prior to Python 3.7, asynchronous generator expressions could
398 only appear in :keyword:`async def` coroutines. Starting
399 with 3.7, any function can use asynchronous generator expressions.
Georg Brandl96593ed2007-09-07 14:15:41 +0000400
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200401.. versionchanged:: 3.8
402 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200403
404
Georg Brandl116aa622007-08-15 14:28:22 +0000405.. _yieldexpr:
406
407Yield expressions
408-----------------
409
410.. index::
411 keyword: yield
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300412 keyword: from
Georg Brandl116aa622007-08-15 14:28:22 +0000413 pair: yield; expression
414 pair: generator; function
415
Victor Stinner8af239e2020-09-18 09:10:15 +0200416.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000417 yield_atom: "(" `yield_expression` ")"
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000418 yield_expression: "yield" [`expression_list` | "from" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Yury Selivanov03660042016-12-15 17:36:05 -0500420The yield expression is used when defining a :term:`generator` function
421or an :term:`asynchronous generator` function and
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500422thus can only be used in the body of a function definition. Using a yield
Yury Selivanov03660042016-12-15 17:36:05 -0500423expression in a function's body causes that function to be a generator,
424and using it in an :keyword:`async def` function's body causes that
425coroutine function to be an asynchronous generator. For example::
426
427 def gen(): # defines a generator function
428 yield 123
429
Andrés Delfinobfe18392018-11-07 15:12:12 -0300430 async def agen(): # defines an asynchronous generator function
Yury Selivanov03660042016-12-15 17:36:05 -0500431 yield 123
432
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200433Due to their side effects on the containing scope, ``yield`` expressions
434are not permitted as part of the implicitly defined scopes used to
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200435implement comprehensions and generator expressions.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200436
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200437.. versionchanged:: 3.8
438 Yield expressions prohibited in the implicitly nested scopes used to
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200439 implement comprehensions and generator expressions.
440
Yury Selivanov03660042016-12-15 17:36:05 -0500441Generator functions are described below, while asynchronous generator
442functions are described separately in section
443:ref:`asynchronous-generator-functions`.
Georg Brandl116aa622007-08-15 14:28:22 +0000444
445When a generator function is called, it returns an iterator known as a
Guido van Rossumd0150ad2015-05-05 12:02:01 -0700446generator. That generator then controls the execution of the generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000447The execution starts when one of the generator's methods is called. At that
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500448time, the execution proceeds to the first yield expression, where it is
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700449suspended again, returning the value of :token:`expression_list` to the generator's
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500450caller. By suspended, we mean that all local state is retained, including the
Ethan Furman2f825af2015-01-14 22:25:27 -0800451current bindings of local variables, the instruction pointer, the internal
452evaluation stack, and the state of any exception handling. When the execution
453is resumed by calling one of the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500454generator's methods, the function can proceed exactly as if the yield expression
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700455were just another external call. The value of the yield expression after
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500456resuming depends on the method which resumed the execution. If
457:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or
458the :func:`next` builtin) then the result is :const:`None`. Otherwise, if
459:meth:`~generator.send` is used, then the result will be the value passed in to
460that method.
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462.. index:: single: coroutine
463
464All of this makes generator functions quite similar to coroutines; they yield
465multiple times, they have more than one entry point and their execution can be
466suspended. The only difference is that a generator function cannot control
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700467where the execution should continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000468transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000469
Ethan Furman2f825af2015-01-14 22:25:27 -0800470Yield expressions are allowed anywhere in a :keyword:`try` construct. If the
471generator is not resumed before it is
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500472finalized (by reaching a zero reference count or by being garbage collected),
473the generator-iterator's :meth:`~generator.close` method will be called,
474allowing any pending :keyword:`finally` clauses to execute.
Georg Brandl02c30562007-09-07 17:52:53 +0000475
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300476.. index::
477 single: from; yield from expression
478
Nick Coghlan0ed80192012-01-14 14:43:24 +1000479When ``yield from <expr>`` is used, it treats the supplied expression as
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000480a subiterator. All values produced by that subiterator are passed directly
481to the caller of the current generator's methods. Any values passed in with
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300482:meth:`~generator.send` and any exceptions passed in with
483:meth:`~generator.throw` are passed to the underlying iterator if it has the
484appropriate methods. If this is not the case, then :meth:`~generator.send`
485will raise :exc:`AttributeError` or :exc:`TypeError`, while
486:meth:`~generator.throw` will just raise the passed in exception immediately.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000487
488When the underlying iterator is complete, the :attr:`~StopIteration.value`
489attribute of the raised :exc:`StopIteration` instance becomes the value of
490the yield expression. It can be either set explicitly when raising
divyag9778a9102019-05-13 08:05:20 -0500491:exc:`StopIteration`, or automatically when the subiterator is a generator
492(by returning a value from the subgenerator).
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000493
Nick Coghlan0ed80192012-01-14 14:43:24 +1000494 .. versionchanged:: 3.3
Martin Panterd21e0b52015-10-10 10:36:22 +0000495 Added ``yield from <expr>`` to delegate control flow to a subiterator.
Nick Coghlan0ed80192012-01-14 14:43:24 +1000496
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500497The parentheses may be omitted when the yield expression is the sole expression
498on the right hand side of an assignment statement.
499
500.. seealso::
501
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300502 :pep:`255` - Simple Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500503 The proposal for adding generators and the :keyword:`yield` statement to Python.
504
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300505 :pep:`342` - Coroutines via Enhanced Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500506 The proposal to enhance the API and syntax of generators, making them
507 usable as simple coroutines.
508
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300509 :pep:`380` - Syntax for Delegating to a Subgenerator
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500510 The proposal to introduce the :token:`yield_from` syntax, making delegation
divyag9778a9102019-05-13 08:05:20 -0500511 to subgenerators easy.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000512
Andrés Delfinobfe18392018-11-07 15:12:12 -0300513 :pep:`525` - Asynchronous Generators
514 The proposal that expanded on :pep:`492` by adding generator capabilities to
515 coroutine functions.
516
Georg Brandl116aa622007-08-15 14:28:22 +0000517.. index:: object: generator
Yury Selivanov66f88282015-06-24 11:04:15 -0400518.. _generator-methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000519
R David Murray2c1d1d62012-08-17 20:48:59 -0400520Generator-iterator methods
521^^^^^^^^^^^^^^^^^^^^^^^^^^
522
523This subsection describes the methods of a generator iterator. They can
524be used to control the execution of a generator function.
525
526Note that calling any of the generator methods below when the generator
527is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529.. index:: exception: StopIteration
530
531
Georg Brandl96593ed2007-09-07 14:15:41 +0000532.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000533
Georg Brandl96593ed2007-09-07 14:15:41 +0000534 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500535 executed yield expression. When a generator function is resumed with a
536 :meth:`~generator.__next__` method, the current yield expression always
537 evaluates to :const:`None`. The execution then continues to the next yield
538 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300539 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500540 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000541 exception is raised.
542
543 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
544 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000545
546
547.. method:: generator.send(value)
548
549 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500550 *value* argument becomes the result of the current yield expression. The
551 :meth:`send` method returns the next value yielded by the generator, or
552 raises :exc:`StopIteration` if the generator exits without yielding another
553 value. When :meth:`send` is called to start the generator, it must be called
554 with :const:`None` as the argument, because there is no yield expression that
555 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000556
557
558.. method:: generator.throw(type[, value[, traceback]])
559
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700560 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000561 and returns the next value yielded by the generator function. If the generator
562 exits without yielding another value, a :exc:`StopIteration` exception is
563 raised. If the generator function does not catch the passed-in exception, or
564 raises a different exception, then that exception propagates to the caller.
565
566.. index:: exception: GeneratorExit
567
568
569.. method:: generator.close()
570
571 Raises a :exc:`GeneratorExit` at the point where the generator function was
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400572 paused. If the generator function then exits gracefully, is already closed,
573 or raises :exc:`GeneratorExit` (by not catching the exception), close
574 returns to its caller. If the generator yields a value, a
575 :exc:`RuntimeError` is raised. If the generator raises any other exception,
576 it is propagated to the caller. :meth:`close` does nothing if the generator
577 has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000578
Chris Jerdonek2654b862012-12-23 15:31:57 -0800579.. index:: single: yield; examples
580
581Examples
582^^^^^^^^
583
Georg Brandl116aa622007-08-15 14:28:22 +0000584Here is a simple example that demonstrates the behavior of generators and
585generator functions::
586
587 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000588 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000589 ... try:
590 ... while True:
591 ... try:
592 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000593 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000594 ... value = e
595 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000596 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000597 ...
598 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000599 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000600 Execution starts when 'next()' is called for the first time.
601 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000602 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000603 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000604 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000605 2
606 >>> generator.throw(TypeError, "spam")
607 TypeError('spam',)
608 >>> generator.close()
609 Don't forget to clean up when 'close()' is called.
610
Chris Jerdonek2654b862012-12-23 15:31:57 -0800611For examples using ``yield from``, see :ref:`pep-380` in "What's New in
612Python."
613
Yury Selivanov03660042016-12-15 17:36:05 -0500614.. _asynchronous-generator-functions:
615
616Asynchronous generator functions
617^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
618
619The presence of a yield expression in a function or method defined using
divyag9778a9102019-05-13 08:05:20 -0500620:keyword:`async def` further defines the function as an
Yury Selivanov03660042016-12-15 17:36:05 -0500621:term:`asynchronous generator` function.
622
623When an asynchronous generator function is called, it returns an
624asynchronous iterator known as an asynchronous generator object.
625That object then controls the execution of the generator function.
626An asynchronous generator object is typically used in an
627:keyword:`async for` statement in a coroutine function analogously to
628how a generator object would be used in a :keyword:`for` statement.
629
630Calling one of the asynchronous generator's methods returns an
631:term:`awaitable` object, and the execution starts when this object
632is awaited on. At that time, the execution proceeds to the first yield
633expression, where it is suspended again, returning the value of
634:token:`expression_list` to the awaiting coroutine. As with a generator,
635suspension means that all local state is retained, including the
636current bindings of local variables, the instruction pointer, the internal
637evaluation stack, and the state of any exception handling. When the execution
638is resumed by awaiting on the next object returned by the asynchronous
639generator's methods, the function can proceed exactly as if the yield
640expression were just another external call. The value of the yield expression
641after resuming depends on the method which resumed the execution. If
642:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
643:meth:`~agen.asend` is used, then the result will be the value passed in to
644that method.
645
Joongi Kim6e8dcda2020-11-02 17:02:48 +0900646If an asynchronous generator happens to exit early by :keyword:`break`, the caller
647task being cancelled, or other exceptions, the generator's async cleanup code
648will run and possibly raise exceptions or access context variables in an
649unexpected context--perhaps after the lifetime of tasks it depends, or
650during the event loop shutdown when the async-generator garbage collection hook
651is called.
652To prevent this, the caller must explicitly close the async generator by calling
653:meth:`~agen.aclose` method to finalize the generator and ultimately detach it
654from the event loop.
655
Yury Selivanov03660042016-12-15 17:36:05 -0500656In an asynchronous generator function, yield expressions are allowed anywhere
657in a :keyword:`try` construct. However, if an asynchronous generator is not
658resumed before it is finalized (by reaching a zero reference count or by
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200659being garbage collected), then a yield expression within a :keyword:`!try`
Yury Selivanov03660042016-12-15 17:36:05 -0500660construct could result in a failure to execute pending :keyword:`finally`
661clauses. In this case, it is the responsibility of the event loop or
662scheduler running the asynchronous generator to call the asynchronous
663generator-iterator's :meth:`~agen.aclose` method and run the resulting
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200664coroutine object, thus allowing any pending :keyword:`!finally` clauses
Yury Selivanov03660042016-12-15 17:36:05 -0500665to execute.
666
Joongi Kim6e8dcda2020-11-02 17:02:48 +0900667To take care of finalization upon event loop termination, an event loop should
668define a *finalizer* function which takes an asynchronous generator-iterator and
669presumably calls :meth:`~agen.aclose` and executes the coroutine.
Yury Selivanov03660042016-12-15 17:36:05 -0500670This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`.
671When first iterated over, an asynchronous generator-iterator will store the
672registered *finalizer* to be called upon finalization. For a reference example
673of a *finalizer* method see the implementation of
674``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`.
675
676The expression ``yield from <expr>`` is a syntax error when used in an
677asynchronous generator function.
678
679.. index:: object: asynchronous-generator
680.. _asynchronous-generator-methods:
681
682Asynchronous generator-iterator methods
683^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
684
685This subsection describes the methods of an asynchronous generator iterator,
686which are used to control the execution of a generator function.
687
688
689.. index:: exception: StopAsyncIteration
690
691.. coroutinemethod:: agen.__anext__()
692
693 Returns an awaitable which when run starts to execute the asynchronous
694 generator or resumes it at the last executed yield expression. When an
divyag9778a9102019-05-13 08:05:20 -0500695 asynchronous generator function is resumed with an :meth:`~agen.__anext__`
Yury Selivanov03660042016-12-15 17:36:05 -0500696 method, the current yield expression always evaluates to :const:`None` in
697 the returned awaitable, which when run will continue to the next yield
698 expression. The value of the :token:`expression_list` of the yield
699 expression is the value of the :exc:`StopIteration` exception raised by
700 the completing coroutine. If the asynchronous generator exits without
divyag9778a9102019-05-13 08:05:20 -0500701 yielding another value, the awaitable instead raises a
Yury Selivanov03660042016-12-15 17:36:05 -0500702 :exc:`StopAsyncIteration` exception, signalling that the asynchronous
703 iteration has completed.
704
705 This method is normally called implicitly by a :keyword:`async for` loop.
706
707
708.. coroutinemethod:: agen.asend(value)
709
710 Returns an awaitable which when run resumes the execution of the
711 asynchronous generator. As with the :meth:`~generator.send()` method for a
712 generator, this "sends" a value into the asynchronous generator function,
713 and the *value* argument becomes the result of the current yield expression.
714 The awaitable returned by the :meth:`asend` method will return the next
715 value yielded by the generator as the value of the raised
716 :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the
717 asynchronous generator exits without yielding another value. When
718 :meth:`asend` is called to start the asynchronous
719 generator, it must be called with :const:`None` as the argument,
720 because there is no yield expression that could receive the value.
721
722
723.. coroutinemethod:: agen.athrow(type[, value[, traceback]])
724
725 Returns an awaitable that raises an exception of type ``type`` at the point
726 where the asynchronous generator was paused, and returns the next value
727 yielded by the generator function as the value of the raised
728 :exc:`StopIteration` exception. If the asynchronous generator exits
divyag9778a9102019-05-13 08:05:20 -0500729 without yielding another value, a :exc:`StopAsyncIteration` exception is
Yury Selivanov03660042016-12-15 17:36:05 -0500730 raised by the awaitable.
731 If the generator function does not catch the passed-in exception, or
delirious-lettuce3378b202017-05-19 14:37:57 -0600732 raises a different exception, then when the awaitable is run that exception
Yury Selivanov03660042016-12-15 17:36:05 -0500733 propagates to the caller of the awaitable.
734
735.. index:: exception: GeneratorExit
736
737
738.. coroutinemethod:: agen.aclose()
739
740 Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
741 the asynchronous generator function at the point where it was paused.
742 If the asynchronous generator function then exits gracefully, is already
743 closed, or raises :exc:`GeneratorExit` (by not catching the exception),
744 then the returned awaitable will raise a :exc:`StopIteration` exception.
745 Any further awaitables returned by subsequent calls to the asynchronous
746 generator will raise a :exc:`StopAsyncIteration` exception. If the
747 asynchronous generator yields a value, a :exc:`RuntimeError` is raised
748 by the awaitable. If the asynchronous generator raises any other exception,
749 it is propagated to the caller of the awaitable. If the asynchronous
750 generator has already exited due to an exception or normal exit, then
751 further calls to :meth:`aclose` will return an awaitable that does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Georg Brandl116aa622007-08-15 14:28:22 +0000753.. _primaries:
754
755Primaries
756=========
757
758.. index:: single: primary
759
760Primaries represent the most tightly bound operations of the language. Their
761syntax is:
762
Victor Stinner8af239e2020-09-18 09:10:15 +0200763.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000764 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
765
766
767.. _attribute-references:
768
769Attribute references
770--------------------
771
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300772.. index::
773 pair: attribute; reference
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200774 single: . (dot); attribute reference
Georg Brandl116aa622007-08-15 14:28:22 +0000775
776An attribute reference is a primary followed by a period and a name:
777
Victor Stinner8af239e2020-09-18 09:10:15 +0200778.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000779 attributeref: `primary` "." `identifier`
780
781.. index::
782 exception: AttributeError
783 object: module
784 object: list
785
786The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000787references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700788attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500789overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700790the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
791the object produced is determined by the object. Multiple evaluations of the
792same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000793
794
795.. _subscriptions:
796
797Subscriptions
798-------------
799
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300800.. index::
801 single: subscription
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200802 single: [] (square brackets); subscription
Georg Brandl116aa622007-08-15 14:28:22 +0000803
804.. index::
805 object: sequence
806 object: mapping
807 object: string
808 object: tuple
809 object: list
810 object: dictionary
811 pair: sequence; item
812
kj7cdf30f2020-10-21 07:38:08 +0800813Subscription of a sequence (string, tuple or list) or mapping (dictionary)
814object usually selects an item from the collection:
Georg Brandl116aa622007-08-15 14:28:22 +0000815
Victor Stinner8af239e2020-09-18 09:10:15 +0200816.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000817 subscription: `primary` "[" `expression_list` "]"
818
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700819The primary must evaluate to an object that supports subscription (lists or
820dictionaries for example). User-defined objects can support subscription by
821defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000822
823For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000824
825If the primary is a mapping, the expression list must evaluate to an object
826whose value is one of the keys of the mapping, and the subscription selects the
827value in the mapping that corresponds to that key. (The expression list is a
828tuple except if it has exactly one item.)
829
Andrés Delfino4fddd4e2018-06-15 15:24:25 -0300830If the primary is a sequence, the expression list must evaluate to an integer
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000831or a slice (as discussed in the following section).
832
833The formal syntax makes no special provision for negative indices in
834sequences; however, built-in sequences all provide a :meth:`__getitem__`
835method that interprets negative indices by adding the length of the sequence
836to the index (so that ``x[-1]`` selects the last item of ``x``). The
837resulting value must be a nonnegative integer less than the number of items in
838the sequence, and the subscription selects the item whose index is that value
839(counting from zero). Since the support for negative indices and slicing
840occurs in the object's :meth:`__getitem__` method, subclasses overriding
841this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000842
843.. index::
844 single: character
845 pair: string; item
846
847A string's items are characters. A character is not a separate data type but a
848string of exactly one character.
849
kj7cdf30f2020-10-21 07:38:08 +0800850Subscription of certain :term:`classes <class>` or :term:`types <type>`
kj9129af62020-10-30 12:01:17 +0800851creates a :ref:`generic alias <types-genericalias>`.
kj7cdf30f2020-10-21 07:38:08 +0800852In this case, user-defined classes can support subscription by providing a
853:meth:`__class_getitem__` classmethod.
854
Georg Brandl116aa622007-08-15 14:28:22 +0000855
856.. _slicings:
857
858Slicings
859--------
860
861.. index::
862 single: slicing
863 single: slice
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200864 single: : (colon); slicing
865 single: , (comma); slicing
Georg Brandl116aa622007-08-15 14:28:22 +0000866
867.. index::
868 object: sequence
869 object: string
870 object: tuple
871 object: list
872
873A slicing selects a range of items in a sequence object (e.g., a string, tuple
874or list). Slicings may be used as expressions or as targets in assignment or
875:keyword:`del` statements. The syntax for a slicing:
876
Victor Stinner8af239e2020-09-18 09:10:15 +0200877.. productionlist:: python-grammar
Georg Brandl48310cd2009-01-03 21:18:54 +0000878 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000879 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000880 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000881 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000882 lower_bound: `expression`
883 upper_bound: `expression`
884 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000885
886There is ambiguity in the formal syntax here: anything that looks like an
887expression list also looks like a slice list, so any subscription can be
888interpreted as a slicing. Rather than further complicating the syntax, this is
889disambiguated by defining that in this case the interpretation as a subscription
890takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000891slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000892
893.. index::
894 single: start (slice object attribute)
895 single: stop (slice object attribute)
896 single: step (slice object attribute)
897
Georg Brandla4c8c472014-10-31 10:38:49 +0100898The semantics for a slicing are as follows. The primary is indexed (using the
899same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000900normal subscription) with a key that is constructed from the slice list, as
901follows. If the slice list contains at least one comma, the key is a tuple
902containing the conversion of the slice items; otherwise, the conversion of the
903lone slice item is the key. The conversion of a slice item that is an
904expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300905object (see section :ref:`types`) whose :attr:`~slice.start`,
906:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
907expressions given as lower bound, upper bound and stride, respectively,
908substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000909
910
Chris Jerdonekb4309942012-12-25 14:54:44 -0800911.. index::
912 object: callable
913 single: call
914 single: argument; call semantics
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200915 single: () (parentheses); call
916 single: , (comma); argument list
917 single: = (equals); in function calls
Chris Jerdonekb4309942012-12-25 14:54:44 -0800918
Georg Brandl116aa622007-08-15 14:28:22 +0000919.. _calls:
920
921Calls
922-----
923
Chris Jerdonekb4309942012-12-25 14:54:44 -0800924A call calls a callable object (e.g., a :term:`function`) with a possibly empty
925series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000926
Victor Stinner8af239e2020-09-18 09:10:15 +0200927.. productionlist:: python-grammar
Georg Brandldc529c12008-09-21 17:03:29 +0000928 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Martin Panter0c0da482016-06-12 01:46:50 +0000929 argument_list: `positional_arguments` ["," `starred_and_keywords`]
930 : ["," `keywords_arguments`]
931 : | `starred_and_keywords` ["," `keywords_arguments`]
932 : | `keywords_arguments`
Brandt Bucher8bae2192020-03-05 21:19:22 -0800933 positional_arguments: positional_item ("," positional_item)*
934 positional_item: `assignment_expression` | "*" `expression`
Martin Panter0c0da482016-06-12 01:46:50 +0000935 starred_and_keywords: ("*" `expression` | `keyword_item`)
936 : ("," "*" `expression` | "," `keyword_item`)*
937 keywords_arguments: (`keyword_item` | "**" `expression`)
Martin Panter7106a512016-12-24 10:20:38 +0000938 : ("," `keyword_item` | "," "**" `expression`)*
Georg Brandl116aa622007-08-15 14:28:22 +0000939 keyword_item: `identifier` "=" `expression`
940
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700941An optional trailing comma may be present after the positional and keyword arguments
942but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000943
Chris Jerdonekb4309942012-12-25 14:54:44 -0800944.. index::
945 single: parameter; call semantics
946
Georg Brandl116aa622007-08-15 14:28:22 +0000947The primary must evaluate to a callable object (user-defined functions, built-in
948functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000949instances, and all objects having a :meth:`__call__` method are callable). All
950argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800951to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000952
953.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955If keyword arguments are present, they are first converted to positional
956arguments, as follows. First, a list of unfilled slots is created for the
957formal parameters. If there are N positional arguments, they are placed in the
958first N slots. Next, for each keyword argument, the identifier is used to
959determine the corresponding slot (if the identifier is the same as the first
960formal parameter name, the first slot is used, and so on). If the slot is
961already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
962the argument is placed in the slot, filling it (even if the expression is
963``None``, it fills the slot). When all arguments have been processed, the slots
964that are still unfilled are filled with the corresponding default value from the
965function definition. (Default values are calculated, once, when the function is
966defined; thus, a mutable object such as a list or dictionary used as default
967value will be shared by all calls that don't specify an argument value for the
968corresponding slot; this should usually be avoided.) If there are any unfilled
969slots for which no default value is specified, a :exc:`TypeError` exception is
970raised. Otherwise, the list of filled slots is used as the argument list for
971the call.
972
Georg Brandl495f7b52009-10-27 15:28:25 +0000973.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000974
Georg Brandl495f7b52009-10-27 15:28:25 +0000975 An implementation may provide built-in functions whose positional parameters
976 do not have names, even if they are 'named' for the purpose of documentation,
977 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000978 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000979 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000980
Georg Brandl116aa622007-08-15 14:28:22 +0000981If there are more positional arguments than there are formal parameter slots, a
982:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
983``*identifier`` is present; in this case, that formal parameter receives a tuple
984containing the excess positional arguments (or an empty tuple if there were no
985excess positional arguments).
986
987If any keyword argument does not correspond to a formal parameter name, a
988:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
989``**identifier`` is present; in this case, that formal parameter receives a
990dictionary containing the excess keyword arguments (using the keywords as keys
991and the argument values as corresponding values), or a (new) empty dictionary if
992there were no excess keyword arguments.
993
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300994.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200995 single: * (asterisk); in function calls
Martin Panter0c0da482016-06-12 01:46:50 +0000996 single: unpacking; in function calls
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300997
Georg Brandl116aa622007-08-15 14:28:22 +0000998If the syntax ``*expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +0000999evaluate to an :term:`iterable`. Elements from these iterables are
1000treated as if they were additional positional arguments. For the call
1001``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*,
1002this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
1003*y1*, ..., *yM*, *x3*, *x4*.
Georg Brandl116aa622007-08-15 14:28:22 +00001004
Benjamin Peterson2d735bc2008-08-19 20:57:10 +00001005A consequence of this is that although the ``*expression`` syntax may appear
Martin Panter0c0da482016-06-12 01:46:50 +00001006*after* explicit keyword arguments, it is processed *before* the
1007keyword arguments (and any ``**expression`` arguments -- see below). So::
Georg Brandl116aa622007-08-15 14:28:22 +00001008
1009 >>> def f(a, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001010 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +00001011 ...
1012 >>> f(b=1, *(2,))
1013 2 1
1014 >>> f(a=1, *(2,))
1015 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +05301016 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +00001017 TypeError: f() got multiple values for keyword argument 'a'
1018 >>> f(1, *(2,))
1019 1 2
1020
1021It is unusual for both keyword arguments and the ``*expression`` syntax to be
1022used in the same call, so in practice this confusion does not arise.
1023
Eli Bendersky7bd081c2011-07-30 07:05:16 +03001024.. index::
1025 single: **; in function calls
1026
Georg Brandl116aa622007-08-15 14:28:22 +00001027If the syntax ``**expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +00001028evaluate to a :term:`mapping`, the contents of which are treated as
1029additional keyword arguments. If a keyword is already present
1030(as an explicit keyword argument, or from another unpacking),
1031a :exc:`TypeError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001032
1033Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
1034used as positional argument slots or as keyword argument names.
1035
Martin Panter0c0da482016-06-12 01:46:50 +00001036.. versionchanged:: 3.5
1037 Function calls accept any number of ``*`` and ``**`` unpackings,
1038 positional arguments may follow iterable unpackings (``*``),
1039 and keyword arguments may follow dictionary unpackings (``**``).
1040 Originally proposed by :pep:`448`.
1041
Georg Brandl116aa622007-08-15 14:28:22 +00001042A call always returns some value, possibly ``None``, unless it raises an
1043exception. How this value is computed depends on the type of the callable
1044object.
1045
1046If it is---
1047
1048a user-defined function:
1049 .. index::
1050 pair: function; call
1051 triple: user-defined; function; call
1052 object: user-defined function
1053 object: function
1054
1055 The code block for the function is executed, passing it the argument list. The
1056 first thing the code block will do is bind the formal parameters to the
1057 arguments; this is described in section :ref:`function`. When the code block
1058 executes a :keyword:`return` statement, this specifies the return value of the
1059 function call.
1060
1061a built-in function or method:
1062 .. index::
1063 pair: function; call
1064 pair: built-in function; call
1065 pair: method; call
1066 pair: built-in method; call
1067 object: built-in method
1068 object: built-in function
1069 object: method
1070 object: function
1071
1072 The result is up to the interpreter; see :ref:`built-in-funcs` for the
1073 descriptions of built-in functions and methods.
1074
1075a class object:
1076 .. index::
1077 object: class
1078 pair: class object; call
1079
1080 A new instance of that class is returned.
1081
1082a class instance method:
1083 .. index::
1084 object: class instance
1085 object: instance
1086 pair: class instance; call
1087
1088 The corresponding user-defined function is called, with an argument list that is
1089 one longer than the argument list of the call: the instance becomes the first
1090 argument.
1091
1092a class instance:
1093 .. index::
1094 pair: instance; call
1095 single: __call__() (object method)
1096
1097 The class must define a :meth:`__call__` method; the effect is then the same as
1098 if that method was called.
1099
1100
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001101.. index:: keyword: await
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001102.. _await:
1103
1104Await expression
1105================
1106
1107Suspend the execution of :term:`coroutine` on an :term:`awaitable` object.
1108Can only be used inside a :term:`coroutine function`.
1109
Victor Stinner8af239e2020-09-18 09:10:15 +02001110.. productionlist:: python-grammar
Serhiy Storchakac7cc9852016-05-08 21:59:46 +03001111 await_expr: "await" `primary`
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001112
1113.. versionadded:: 3.5
1114
1115
Georg Brandl116aa622007-08-15 14:28:22 +00001116.. _power:
1117
1118The power operator
1119==================
1120
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001121.. index::
1122 pair: power; operation
1123 operator: **
1124
Georg Brandl116aa622007-08-15 14:28:22 +00001125The power operator binds more tightly than unary operators on its left; it binds
1126less tightly than unary operators on its right. The syntax is:
1127
Victor Stinner8af239e2020-09-18 09:10:15 +02001128.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001129 power: (`await_expr` | `primary`) ["**" `u_expr`]
Georg Brandl116aa622007-08-15 14:28:22 +00001130
1131Thus, in an unparenthesized sequence of power and unary operators, the operators
1132are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +00001133for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001134
1135The power operator has the same semantics as the built-in :func:`pow` function,
1136when called with two arguments: it yields its left argument raised to the power
1137of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +00001138type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +00001139
Georg Brandl96593ed2007-09-07 14:15:41 +00001140For int operands, the result has the same type as the operands unless the second
1141argument is negative; in that case, all arguments are converted to float and a
1142float result is delivered. For example, ``10**2`` returns ``100``, but
1143``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +00001144
1145Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +00001146Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001147number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001148
1149
1150.. _unary:
1151
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001152Unary arithmetic and bitwise operations
1153=======================================
Georg Brandl116aa622007-08-15 14:28:22 +00001154
1155.. index::
1156 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +00001157 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001158
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001159All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +00001160
Victor Stinner8af239e2020-09-18 09:10:15 +02001161.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +00001162 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
1163
1164.. index::
1165 single: negation
1166 single: minus
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001167 single: operator; - (minus)
1168 single: - (minus); unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001169
1170The unary ``-`` (minus) operator yields the negation of its numeric argument.
1171
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001172.. index::
1173 single: plus
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001174 single: operator; + (plus)
1175 single: + (plus); unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001176
1177The unary ``+`` (plus) operator yields its numeric argument unchanged.
1178
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001179.. index::
1180 single: inversion
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001181 operator: ~ (tilde)
Christian Heimesfaf2f632008-01-06 16:59:19 +00001182
Georg Brandl95817b32008-05-11 14:30:18 +00001183The unary ``~`` (invert) operator yields the bitwise inversion of its integer
1184argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
1185applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00001186
1187.. index:: exception: TypeError
1188
1189In all three cases, if the argument does not have the proper type, a
1190:exc:`TypeError` exception is raised.
1191
1192
1193.. _binary:
1194
1195Binary arithmetic operations
1196============================
1197
1198.. index:: triple: binary; arithmetic; operation
1199
1200The binary arithmetic operations have the conventional priority levels. Note
1201that some of these operations also apply to certain non-numeric types. Apart
1202from the power operator, there are only two levels, one for multiplicative
1203operators and one for additive operators:
1204
Victor Stinner8af239e2020-09-18 09:10:15 +02001205.. productionlist:: python-grammar
Benjamin Petersond51374e2014-04-09 23:55:56 -04001206 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
Andrés Delfinocaccca782018-07-07 17:24:46 -03001207 : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` |
Benjamin Petersond51374e2014-04-09 23:55:56 -04001208 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001209 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
1210
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001211.. index::
1212 single: multiplication
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001213 operator: * (asterisk)
Georg Brandl116aa622007-08-15 14:28:22 +00001214
1215The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +00001216arguments must either both be numbers, or one argument must be an integer and
1217the other must be a sequence. In the former case, the numbers are converted to a
1218common type and then multiplied together. In the latter case, sequence
1219repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001220
Andrés Delfino69511862018-06-15 16:23:00 -03001221.. index::
1222 single: matrix multiplication
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001223 operator: @ (at)
Benjamin Petersond51374e2014-04-09 23:55:56 -04001224
1225The ``@`` (at) operator is intended to be used for matrix multiplication. No
1226builtin Python types implement this operator.
1227
1228.. versionadded:: 3.5
1229
Georg Brandl116aa622007-08-15 14:28:22 +00001230.. index::
1231 exception: ZeroDivisionError
1232 single: division
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001233 operator: / (slash)
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001234 operator: //
Georg Brandl116aa622007-08-15 14:28:22 +00001235
1236The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
1237their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +02001238Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +00001239integer; the result is that of mathematical division with the 'floor' function
1240applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
1241exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001242
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001243.. index::
1244 single: modulo
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001245 operator: % (percent)
Georg Brandl116aa622007-08-15 14:28:22 +00001246
1247The ``%`` (modulo) operator yields the remainder from the division of the first
1248argument by the second. The numeric arguments are first converted to a common
1249type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
1250arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
1251(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
1252result with the same sign as its second operand (or zero); the absolute value of
1253the result is strictly smaller than the absolute value of the second operand
1254[#]_.
1255
Georg Brandl96593ed2007-09-07 14:15:41 +00001256The floor division and modulo operators are connected by the following
1257identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
1258connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
1259x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +00001260
1261In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +00001262also overloaded by string objects to perform old-style string formatting (also
1263known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +00001264Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +00001265
1266The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +00001267function are not defined for complex numbers. Instead, convert to a floating
1268point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +00001269
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001270.. index::
1271 single: addition
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001272 single: operator; + (plus)
1273 single: + (plus); binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001274
Georg Brandl96593ed2007-09-07 14:15:41 +00001275The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001276must either both be numbers or both be sequences of the same type. In the
1277former case, the numbers are converted to a common type and then added together.
1278In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +00001279
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001280.. index::
1281 single: subtraction
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001282 single: operator; - (minus)
1283 single: - (minus); binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001284
1285The ``-`` (subtraction) operator yields the difference of its arguments. The
1286numeric arguments are first converted to a common type.
1287
1288
1289.. _shifting:
1290
1291Shifting operations
1292===================
1293
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001294.. index::
1295 pair: shifting; operation
1296 operator: <<
1297 operator: >>
Georg Brandl116aa622007-08-15 14:28:22 +00001298
1299The shifting operations have lower priority than the arithmetic operations:
1300
Victor Stinner8af239e2020-09-18 09:10:15 +02001301.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001302 shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001303
Georg Brandl96593ed2007-09-07 14:15:41 +00001304These operators accept integers as arguments. They shift the first argument to
1305the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001306
1307.. index:: exception: ValueError
1308
Georg Brandl0aaae262013-10-08 21:47:18 +02001309A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
1310shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001311
1312
1313.. _bitwise:
1314
Christian Heimesfaf2f632008-01-06 16:59:19 +00001315Binary bitwise operations
1316=========================
Georg Brandl116aa622007-08-15 14:28:22 +00001317
Christian Heimesfaf2f632008-01-06 16:59:19 +00001318.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001319
1320Each of the three bitwise operations has a different priority level:
1321
Victor Stinner8af239e2020-09-18 09:10:15 +02001322.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +00001323 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1324 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1325 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1326
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001327.. index::
1328 pair: bitwise; and
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001329 operator: & (ampersand)
Georg Brandl116aa622007-08-15 14:28:22 +00001330
Georg Brandl96593ed2007-09-07 14:15:41 +00001331The ``&`` operator yields the bitwise AND of its arguments, which must be
1332integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001333
1334.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001335 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001336 pair: exclusive; or
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001337 operator: ^ (caret)
Georg Brandl116aa622007-08-15 14:28:22 +00001338
1339The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001340must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001341
1342.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001343 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001344 pair: inclusive; or
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001345 operator: | (vertical bar)
Georg Brandl116aa622007-08-15 14:28:22 +00001346
1347The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001348must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001349
1350
1351.. _comparisons:
1352
1353Comparisons
1354===========
1355
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001356.. index::
1357 single: comparison
1358 pair: C; language
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001359 operator: < (less)
1360 operator: > (greater)
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001361 operator: <=
1362 operator: >=
1363 operator: ==
1364 operator: !=
Georg Brandl116aa622007-08-15 14:28:22 +00001365
1366Unlike C, all comparison operations in Python have the same priority, which is
1367lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1368C, expressions like ``a < b < c`` have the interpretation that is conventional
1369in mathematics:
1370
Victor Stinner8af239e2020-09-18 09:10:15 +02001371.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001372 comparison: `or_expr` (`comp_operator` `or_expr`)*
Georg Brandl116aa622007-08-15 14:28:22 +00001373 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1374 : | "is" ["not"] | ["not"] "in"
1375
1376Comparisons yield boolean values: ``True`` or ``False``.
1377
1378.. index:: pair: chaining; comparisons
1379
1380Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1381``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1382cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1383
Guido van Rossum04110fb2007-08-24 16:32:05 +00001384Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1385*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1386to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1387evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001388
Guido van Rossum04110fb2007-08-24 16:32:05 +00001389Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001390*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1391pretty).
1392
Martin Panteraa0da862015-09-23 05:28:13 +00001393Value comparisons
1394-----------------
1395
Georg Brandl116aa622007-08-15 14:28:22 +00001396The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
Martin Panteraa0da862015-09-23 05:28:13 +00001397values of two objects. The objects do not need to have the same type.
Georg Brandl116aa622007-08-15 14:28:22 +00001398
Martin Panteraa0da862015-09-23 05:28:13 +00001399Chapter :ref:`objects` states that objects have a value (in addition to type
1400and identity). The value of an object is a rather abstract notion in Python:
1401For example, there is no canonical access method for an object's value. Also,
1402there is no requirement that the value of an object should be constructed in a
1403particular way, e.g. comprised of all its data attributes. Comparison operators
1404implement a particular notion of what the value of an object is. One can think
1405of them as defining the value of an object indirectly, by means of their
1406comparison implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00001407
Martin Panteraa0da862015-09-23 05:28:13 +00001408Because all types are (direct or indirect) subtypes of :class:`object`, they
1409inherit the default comparison behavior from :class:`object`. Types can
1410customize their comparison behavior by implementing
1411:dfn:`rich comparison methods` like :meth:`__lt__`, described in
1412:ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001413
Martin Panteraa0da862015-09-23 05:28:13 +00001414The default behavior for equality comparison (``==`` and ``!=``) is based on
1415the identity of the objects. Hence, equality comparison of instances with the
1416same identity results in equality, and equality comparison of instances with
1417different identities results in inequality. A motivation for this default
1418behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1419implies ``x == y``).
1420
1421A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1422an attempt raises :exc:`TypeError`. A motivation for this default behavior is
1423the lack of a similar invariant as for equality.
1424
1425The behavior of the default equality comparison, that instances with different
1426identities are always unequal, may be in contrast to what types will need that
1427have a sensible definition of object value and value-based equality. Such
1428types will need to customize their comparison behavior, and in fact, a number
1429of built-in types have done that.
1430
1431The following list describes the comparison behavior of the most important
1432built-in types.
1433
1434* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1435 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
1436 compared within and across their types, with the restriction that complex
1437 numbers do not support order comparison. Within the limits of the types
1438 involved, they compare mathematically (algorithmically) correct without loss
1439 of precision.
1440
Tony Fluryad8a0002018-09-14 18:48:50 +01001441 The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are
1442 special. Any ordered comparison of a number to a not-a-number value is false.
1443 A counter-intuitive implication is that not-a-number values are not equal to
Mark Dickinson810f68f2020-04-05 10:25:24 +01001444 themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3`` and
1445 ``x == x`` are all false, while ``x != x`` is true. This behavior is
1446 compliant with IEEE 754.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001447
Raymond Hettingeredd21122019-08-24 10:43:55 -07001448* ``None`` and ``NotImplemented`` are singletons. :PEP:`8` advises that
1449 comparisons for singletons should always be done with ``is`` or ``is not``,
1450 never the equality operators.
1451
Martin Panteraa0da862015-09-23 05:28:13 +00001452* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
1453 compared within and across their types. They compare lexicographically using
1454 the numeric values of their elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001455
Martin Panteraa0da862015-09-23 05:28:13 +00001456* Strings (instances of :class:`str`) compare lexicographically using the
1457 numerical Unicode code points (the result of the built-in function
1458 :func:`ord`) of their characters. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001459
Martin Panteraa0da862015-09-23 05:28:13 +00001460 Strings and binary sequences cannot be directly compared.
Georg Brandl116aa622007-08-15 14:28:22 +00001461
Martin Panteraa0da862015-09-23 05:28:13 +00001462* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can
1463 be compared only within each of their types, with the restriction that ranges
1464 do not support order comparison. Equality comparison across these types
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +02001465 results in inequality, and ordering comparison across these types raises
Martin Panteraa0da862015-09-23 05:28:13 +00001466 :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001467
Martin Panteraa0da862015-09-23 05:28:13 +00001468 Sequences compare lexicographically using comparison of corresponding
Raymond Hettingeredd21122019-08-24 10:43:55 -07001469 elements. The built-in containers typically assume identical objects are
1470 equal to themselves. That lets them bypass equality tests for identical
1471 objects to improve performance and to maintain their internal invariants.
Martin Panteraa0da862015-09-23 05:28:13 +00001472
1473 Lexicographical comparison between built-in collections works as follows:
1474
1475 - For two collections to compare equal, they must be of the same type, have
1476 the same length, and each pair of corresponding elements must compare
1477 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1478 same).
1479
1480 - Collections that support order comparison are ordered the same as their
1481 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same
1482 value as ``x <= y``). If a corresponding element does not exist, the
1483 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1484 true).
1485
1486* Mappings (instances of :class:`dict`) compare equal if and only if they have
cocoatomocdcac032017-03-31 14:48:49 +09001487 equal `(key, value)` pairs. Equality comparison of the keys and values
Martin Panteraa0da862015-09-23 05:28:13 +00001488 enforces reflexivity.
1489
1490 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
1491
1492* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within
1493 and across their types.
1494
1495 They define order
1496 comparison operators to mean subset and superset tests. Those relations do
1497 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}``
1498 are not equal, nor subsets of one another, nor supersets of one
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001499 another). Accordingly, sets are not appropriate arguments for functions
Martin Panteraa0da862015-09-23 05:28:13 +00001500 which depend on total ordering (for example, :func:`min`, :func:`max`, and
1501 :func:`sorted` produce undefined results given a list of sets as inputs).
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001502
Martin Panteraa0da862015-09-23 05:28:13 +00001503 Comparison of sets enforces reflexivity of its elements.
Georg Brandl116aa622007-08-15 14:28:22 +00001504
Martin Panteraa0da862015-09-23 05:28:13 +00001505* Most other built-in types have no comparison methods implemented, so they
1506 inherit the default comparison behavior.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001507
Martin Panteraa0da862015-09-23 05:28:13 +00001508User-defined classes that customize their comparison behavior should follow
1509some consistency rules, if possible:
1510
1511* Equality comparison should be reflexive.
1512 In other words, identical objects should compare equal:
1513
1514 ``x is y`` implies ``x == y``
1515
1516* Comparison should be symmetric.
1517 In other words, the following expressions should have the same result:
1518
1519 ``x == y`` and ``y == x``
1520
1521 ``x != y`` and ``y != x``
1522
1523 ``x < y`` and ``y > x``
1524
1525 ``x <= y`` and ``y >= x``
1526
1527* Comparison should be transitive.
1528 The following (non-exhaustive) examples illustrate that:
1529
1530 ``x > y and y > z`` implies ``x > z``
1531
1532 ``x < y and y <= z`` implies ``x < z``
1533
1534* Inverse comparison should result in the boolean negation.
1535 In other words, the following expressions should have the same result:
1536
1537 ``x == y`` and ``not x != y``
1538
1539 ``x < y`` and ``not x >= y`` (for total ordering)
1540
1541 ``x > y`` and ``not x <= y`` (for total ordering)
1542
1543 The last two expressions apply to totally ordered collections (e.g. to
1544 sequences, but not to sets or mappings). See also the
1545 :func:`~functools.total_ordering` decorator.
1546
Martin Panter8dbb0ca2017-01-29 10:00:23 +00001547* The :func:`hash` result should be consistent with equality.
1548 Objects that are equal should either have the same hash value,
1549 or be marked as unhashable.
1550
Martin Panteraa0da862015-09-23 05:28:13 +00001551Python does not enforce these consistency rules. In fact, the not-a-number
1552values are an example for not following these rules.
1553
1554
1555.. _in:
1556.. _not in:
Georg Brandl495f7b52009-10-27 15:28:25 +00001557.. _membership-test-details:
1558
Martin Panteraa0da862015-09-23 05:28:13 +00001559Membership test operations
1560--------------------------
1561
Georg Brandl96593ed2007-09-07 14:15:41 +00001562The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301563s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
1564``x not in s`` returns the negation of ``x in s``. All built-in sequences and
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001565set types support this as well as dictionary, for which :keyword:`!in` tests
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301566whether the dictionary has a given key. For container types such as list, tuple,
1567set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001568to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001569
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301570For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
Georg Brandl4b491312007-08-31 09:22:56 +00001571substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1572always considered to be a substring of any other string, so ``"" in "abc"`` will
1573return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001574
Georg Brandl116aa622007-08-15 14:28:22 +00001575For user-defined classes which define the :meth:`__contains__` method, ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301576y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and
1577``False`` otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001578
Georg Brandl495f7b52009-10-27 15:28:25 +00001579For user-defined classes which do not define :meth:`__contains__` but do define
Antti Haapala2f5b9dc2019-05-30 23:19:29 +03001580:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z``, for which the
1581expression ``x is z or x == z`` is true, is produced while iterating over ``y``.
1582If an exception is raised during the iteration, it is as if :keyword:`in` raised
1583that exception.
Georg Brandl495f7b52009-10-27 15:28:25 +00001584
1585Lastly, the old-style iteration protocol is tried: if a class defines
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301586:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
Antti Haapala2f5b9dc2019-05-30 23:19:29 +03001587integer index *i* such that ``x is y[i] or x == y[i]``, and no lower integer index
1588raises the :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001589if :keyword:`in` raised that exception).
1590
1591.. index::
1592 operator: in
1593 operator: not in
1594 pair: membership; test
1595 object: sequence
1596
divyag9778a9102019-05-13 08:05:20 -05001597The operator :keyword:`not in` is defined to have the inverse truth value of
Georg Brandl116aa622007-08-15 14:28:22 +00001598:keyword:`in`.
1599
1600.. index::
1601 operator: is
1602 operator: is not
1603 pair: identity; test
1604
Martin Panteraa0da862015-09-23 05:28:13 +00001605
1606.. _is:
1607.. _is not:
1608
1609Identity comparisons
1610--------------------
1611
divyag9778a9102019-05-13 08:05:20 -05001612The operators :keyword:`is` and :keyword:`is not` test for an object's identity: ``x
1613is 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 -07001614is determined using the :meth:`id` function. ``x is not y`` yields the inverse
1615truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001616
1617
1618.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001619.. _and:
1620.. _or:
1621.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001622
1623Boolean operations
1624==================
1625
1626.. index::
1627 pair: Conditional; expression
1628 pair: Boolean; operation
1629
Victor Stinner8af239e2020-09-18 09:10:15 +02001630.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +00001631 or_test: `and_test` | `or_test` "or" `and_test`
1632 and_test: `not_test` | `and_test` "and" `not_test`
1633 not_test: `comparison` | "not" `not_test`
1634
1635In the context of Boolean operations, and also when expressions are used by
1636control flow statements, the following values are interpreted as false:
1637``False``, ``None``, numeric zero of all types, and empty strings and containers
1638(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001639other values are interpreted as true. User-defined objects can customize their
1640truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001641
1642.. index:: operator: not
1643
1644The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1645otherwise.
1646
Georg Brandl116aa622007-08-15 14:28:22 +00001647.. index:: operator: and
1648
1649The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1650returned; otherwise, *y* is evaluated and the resulting value is returned.
1651
1652.. index:: operator: or
1653
1654The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1655returned; otherwise, *y* is evaluated and the resulting value is returned.
1656
Andre Delfino55f41e42018-12-05 16:45:30 -03001657Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
Georg Brandl116aa622007-08-15 14:28:22 +00001658they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001659argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001660replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001661the desired value. Because :keyword:`not` has to create a new value, it
1662returns a boolean value regardless of the type of its argument
1663(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001664
1665
Brandt Bucher8bae2192020-03-05 21:19:22 -08001666Assignment expressions
1667======================
1668
Victor Stinner8af239e2020-09-18 09:10:15 +02001669.. productionlist:: python-grammar
Brandt Bucher8bae2192020-03-05 21:19:22 -08001670 assignment_expression: [`identifier` ":="] `expression`
1671
Shankar Jhaf117cef2020-07-26 05:03:48 +05301672An assignment expression (sometimes also called a "named expression" or
1673"walrus") assigns an :token:`expression` to an :token:`identifier`, while also
1674returning the value of the :token:`expression`.
Brandt Bucher8bae2192020-03-05 21:19:22 -08001675
Shankar Jhaf117cef2020-07-26 05:03:48 +05301676One common use case is when handling matched regular expressions:
1677
1678.. code-block:: python
1679
1680 if matching := pattern.search(data):
1681 do_something(matching)
1682
1683Or, when processing a file stream in chunks:
1684
1685.. code-block:: python
1686
1687 while chunk := file.read(9000):
1688 process(chunk)
1689
1690.. versionadded:: 3.8
1691 See :pep:`572` for more details about assignment expressions.
Brandt Bucher8bae2192020-03-05 21:19:22 -08001692
1693
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001694.. _if_expr:
1695
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001696Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001697=======================
1698
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001699.. index::
1700 pair: conditional; expression
1701 pair: ternary; operator
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001702 single: if; conditional expression
1703 single: else; conditional expression
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001704
Victor Stinner8af239e2020-09-18 09:10:15 +02001705.. productionlist:: python-grammar
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001706 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001707 expression: `conditional_expression` | `lambda_expr`
1708 expression_nocond: `or_test` | `lambda_expr_nocond`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001709
1710Conditional expressions (sometimes called a "ternary operator") have the lowest
1711priority of all Python operations.
1712
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001713The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1714If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001715evaluated and its value is returned.
1716
1717See :pep:`308` for more details about conditional expressions.
1718
1719
Georg Brandl116aa622007-08-15 14:28:22 +00001720.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001721.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001722
1723Lambdas
1724=======
1725
1726.. index::
1727 pair: lambda; expression
1728 pair: lambda; form
1729 pair: anonymous; function
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001730 single: : (colon); lambda expression
Georg Brandl116aa622007-08-15 14:28:22 +00001731
Victor Stinner8af239e2020-09-18 09:10:15 +02001732.. productionlist:: python-grammar
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001733 lambda_expr: "lambda" [`parameter_list`] ":" `expression`
1734 lambda_expr_nocond: "lambda" [`parameter_list`] ":" `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001735
Zachary Ware2f78b842014-06-03 09:32:40 -05001736Lambda expressions (sometimes called lambda forms) are used to create anonymous
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001737functions. The expression ``lambda parameters: expression`` yields a function
Martin Panter1050d2d2016-07-26 11:18:21 +02001738object. The unnamed object behaves like a function object defined with:
1739
1740.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +00001741
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001742 def <lambda>(parameters):
Georg Brandl116aa622007-08-15 14:28:22 +00001743 return expression
1744
1745See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001746functions created with lambda expressions cannot contain statements or
1747annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001748
Georg Brandl116aa622007-08-15 14:28:22 +00001749
1750.. _exprlists:
1751
1752Expression lists
1753================
1754
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001755.. index::
1756 pair: expression; list
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001757 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +00001758
Victor Stinner8af239e2020-09-18 09:10:15 +02001759.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001760 expression_list: `expression` ("," `expression`)* [","]
1761 starred_list: `starred_item` ("," `starred_item`)* [","]
1762 starred_expression: `expression` | (`starred_item` ",")* [`starred_item`]
Brandt Bucher8bae2192020-03-05 21:19:22 -08001763 starred_item: `assignment_expression` | "*" `or_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001764
1765.. index:: object: tuple
1766
Martin Panter0c0da482016-06-12 01:46:50 +00001767Except when part of a list or set display, an expression list
1768containing at least one comma yields a tuple. The length of
Georg Brandl116aa622007-08-15 14:28:22 +00001769the tuple is the number of expressions in the list. The expressions are
1770evaluated from left to right.
1771
Martin Panter0c0da482016-06-12 01:46:50 +00001772.. index::
1773 pair: iterable; unpacking
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001774 single: * (asterisk); in expression lists
Martin Panter0c0da482016-06-12 01:46:50 +00001775
1776An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be
1777an :term:`iterable`. The iterable is expanded into a sequence of items,
1778which are included in the new tuple, list, or set, at the site of
1779the unpacking.
1780
1781.. versionadded:: 3.5
1782 Iterable unpacking in expression lists, originally proposed by :pep:`448`.
1783
Georg Brandl116aa622007-08-15 14:28:22 +00001784.. index:: pair: trailing; comma
1785
1786The trailing comma is required only to create a single tuple (a.k.a. a
1787*singleton*); it is optional in all other cases. A single expression without a
1788trailing comma doesn't create a tuple, but rather yields the value of that
1789expression. (To create an empty tuple, use an empty pair of parentheses:
1790``()``.)
1791
1792
1793.. _evalorder:
1794
1795Evaluation order
1796================
1797
1798.. index:: pair: evaluation; order
1799
Georg Brandl96593ed2007-09-07 14:15:41 +00001800Python evaluates expressions from left to right. Notice that while evaluating
1801an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001802
1803In the following lines, expressions will be evaluated in the arithmetic order of
1804their suffixes::
1805
1806 expr1, expr2, expr3, expr4
1807 (expr1, expr2, expr3, expr4)
1808 {expr1: expr2, expr3: expr4}
1809 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001810 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001811 expr3, expr4 = expr1, expr2
1812
1813
1814.. _operator-summary:
1815
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001816Operator precedence
1817===================
Georg Brandl116aa622007-08-15 14:28:22 +00001818
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001819.. index::
1820 pair: operator; precedence
Georg Brandl116aa622007-08-15 14:28:22 +00001821
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001822The following table summarizes the operator precedence in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001823precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001824the same box have the same precedence. Unless the syntax is explicitly given,
1825operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001826exponentiation, which groups from right to left).
1827
1828Note that comparisons, membership tests, and identity tests, all have the same
1829precedence and have a left-to-right chaining feature as described in the
1830:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001831
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001832
1833+-----------------------------------------------+-------------------------------------+
1834| Operator | Description |
1835+===============================================+=====================================+
Emily Morehouse6357c952019-09-11 15:37:12 +01001836| ``:=`` | Assignment expression |
1837+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001838| :keyword:`lambda` | Lambda expression |
1839+-----------------------------------------------+-------------------------------------+
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001840| :keyword:`if <if_expr>` -- :keyword:`!else` | Conditional expression |
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001841+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001842| :keyword:`or` | Boolean OR |
1843+-----------------------------------------------+-------------------------------------+
1844| :keyword:`and` | Boolean AND |
1845+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001846| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001847+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001848| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001849| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001850| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001851+-----------------------------------------------+-------------------------------------+
1852| ``|`` | Bitwise OR |
1853+-----------------------------------------------+-------------------------------------+
1854| ``^`` | Bitwise XOR |
1855+-----------------------------------------------+-------------------------------------+
1856| ``&`` | Bitwise AND |
1857+-----------------------------------------------+-------------------------------------+
1858| ``<<``, ``>>`` | Shifts |
1859+-----------------------------------------------+-------------------------------------+
1860| ``+``, ``-`` | Addition and subtraction |
1861+-----------------------------------------------+-------------------------------------+
Benjamin Petersond51374e2014-04-09 23:55:56 -04001862| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
svelankar9b47af62017-09-17 20:56:16 -04001863| | multiplication, division, floor |
1864| | division, remainder [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001865+-----------------------------------------------+-------------------------------------+
1866| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1867+-----------------------------------------------+-------------------------------------+
1868| ``**`` | Exponentiation [#]_ |
1869+-----------------------------------------------+-------------------------------------+
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001870| :keyword:`await` ``x`` | Await expression |
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001871+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001872| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1873| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1874+-----------------------------------------------+-------------------------------------+
Andre Delfinodc269972019-09-11 10:16:11 -03001875| ``(expressions...)``, | Binding or parenthesized |
1876| | expression, |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001877| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001878| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001879| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001880+-----------------------------------------------+-------------------------------------+
1881
Georg Brandl116aa622007-08-15 14:28:22 +00001882
1883.. rubric:: Footnotes
1884
Georg Brandl116aa622007-08-15 14:28:22 +00001885.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1886 true numerically due to roundoff. For example, and assuming a platform on which
1887 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1888 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001889 1e100``, which is numerically exactly equal to ``1e100``. The function
1890 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001891 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1892 is more appropriate depends on the application.
1893
1894.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001895 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001896 cases, Python returns the latter result, in order to preserve that
1897 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1898
Martin Panteraa0da862015-09-23 05:28:13 +00001899.. [#] The Unicode standard distinguishes between :dfn:`code points`
1900 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
1901 While most abstract characters in Unicode are only represented using one
1902 code point, there is a number of abstract characters that can in addition be
1903 represented using a sequence of more than one code point. For example, the
1904 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
1905 as a single :dfn:`precomposed character` at code position U+00C7, or as a
1906 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
1907 LETTER C), followed by a :dfn:`combining character` at code position U+0327
1908 (COMBINING CEDILLA).
1909
1910 The comparison operators on strings compare at the level of Unicode code
1911 points. This may be counter-intuitive to humans. For example,
1912 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1913 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".
1914
1915 To compare strings at the level of abstract characters (that is, in a way
1916 intuitive to humans), use :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001917
Georg Brandl48310cd2009-01-03 21:18:54 +00001918.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001919 descriptors, you may notice seemingly unusual behaviour in certain uses of
1920 the :keyword:`is` operator, like those involving comparisons between instance
1921 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001922
Georg Brandl063f2372010-12-01 15:32:43 +00001923.. [#] The ``%`` operator is also used for string formatting; the same
1924 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001925
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001926.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1927 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.