blob: 10e194c90103042766615411ab2eecdea3a912af [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
Ken Jin2edaf6a2021-02-03 05:06:57 +080080.. _private-name-mangling:
81
Georg Brandl116aa622007-08-15 14:28:22 +000082.. index::
83 pair: name; mangling
84 pair: private; names
85
86**Private name mangling:** When an identifier that textually occurs in a class
87definition begins with two or more underscore characters and does not end in two
88or more underscores, it is considered a :dfn:`private name` of that class.
89Private names are transformed to a longer form before code is generated for
Georg Brandldec3b3f2013-04-14 10:13:42 +020090them. The transformation inserts the class name, with leading underscores
91removed and a single underscore inserted, in front of the name. For example,
92the identifier ``__spam`` occurring in a class named ``Ham`` will be transformed
93to ``_Ham__spam``. This transformation is independent of the syntactical
94context in which the identifier is used. If the transformed name is extremely
95long (longer than 255 characters), implementation defined truncation may happen.
96If the class name consists only of underscores, no transformation is done.
Georg Brandl116aa622007-08-15 14:28:22 +000097
Georg Brandl116aa622007-08-15 14:28:22 +000098
99.. _atom-literals:
100
101Literals
102--------
103
104.. index:: single: literal
105
Georg Brandl96593ed2007-09-07 14:15:41 +0000106Python supports string and bytes literals and various numeric literals:
Georg Brandl116aa622007-08-15 14:28:22 +0000107
Victor Stinner8af239e2020-09-18 09:10:15 +0200108.. productionlist:: python-grammar
Georg Brandl96593ed2007-09-07 14:15:41 +0000109 literal: `stringliteral` | `bytesliteral`
110 : | `integer` | `floatnumber` | `imagnumber`
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Georg Brandl96593ed2007-09-07 14:15:41 +0000112Evaluation of a literal yields an object of the given type (string, bytes,
113integer, floating point number, complex number) with the given value. The value
114may be approximated in the case of floating point and imaginary (complex)
Georg Brandl116aa622007-08-15 14:28:22 +0000115literals. See section :ref:`literals` for details.
116
117.. index::
118 triple: immutable; data; type
119 pair: immutable; object
120
Terry Jan Reedyead1de22012-02-17 19:56:58 -0500121All literals correspond to immutable data types, and hence the object's identity
122is less important than its value. Multiple evaluations of literals with the
123same value (either the same occurrence in the program text or a different
124occurrence) may obtain the same object or a different object with the same
125value.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127
128.. _parenthesized:
129
130Parenthesized forms
131-------------------
132
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300133.. index::
134 single: parenthesized form
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200135 single: () (parentheses); tuple display
Georg Brandl116aa622007-08-15 14:28:22 +0000136
137A parenthesized form is an optional expression list enclosed in parentheses:
138
Victor Stinner8af239e2020-09-18 09:10:15 +0200139.. productionlist:: python-grammar
Martin Panter0c0da482016-06-12 01:46:50 +0000140 parenth_form: "(" [`starred_expression`] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000141
142A parenthesized expression list yields whatever that expression list yields: if
143the list contains at least one comma, it yields a tuple; otherwise, it yields
144the single expression that makes up the expression list.
145
146.. index:: pair: empty; tuple
147
148An empty pair of parentheses yields an empty tuple object. Since tuples are
divyag9778a9102019-05-13 08:05:20 -0500149immutable, the same rules as for literals apply (i.e., two occurrences of the empty
Georg Brandl116aa622007-08-15 14:28:22 +0000150tuple may or may not yield the same object).
151
152.. index::
Andre Delfinodc269972019-09-11 10:16:11 -0300153 single: comma
154 single: , (comma)
Georg Brandl116aa622007-08-15 14:28:22 +0000155
156Note that tuples are not formed by the parentheses, but rather by use of the
157comma operator. The exception is the empty tuple, for which parentheses *are*
158required --- allowing unparenthesized "nothing" in expressions would cause
159ambiguities and allow common typos to pass uncaught.
160
161
Georg Brandl96593ed2007-09-07 14:15:41 +0000162.. _comprehensions:
163
164Displays for lists, sets and dictionaries
165-----------------------------------------
166
Florian Dahlitz2d55aa92020-10-20 23:27:07 +0200167.. index:: single: comprehensions
168
Georg Brandl96593ed2007-09-07 14:15:41 +0000169For constructing a list, a set or a dictionary Python provides special syntax
170called "displays", each of them in two flavors:
171
172* either the container contents are listed explicitly, or
173
174* they are computed via a set of looping and filtering instructions, called a
175 :dfn:`comprehension`.
176
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300177.. index::
178 single: for; in comprehensions
179 single: if; in comprehensions
180 single: async for; in comprehensions
181
Georg Brandl96593ed2007-09-07 14:15:41 +0000182Common syntax elements for comprehensions are:
183
Victor Stinner8af239e2020-09-18 09:10:15 +0200184.. productionlist:: python-grammar
Brandt Bucher8bae2192020-03-05 21:19:22 -0800185 comprehension: `assignment_expression` `comp_for`
Serhiy Storchakad08972f2018-04-11 19:15:51 +0300186 comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`]
Georg Brandl96593ed2007-09-07 14:15:41 +0000187 comp_iter: `comp_for` | `comp_if`
Saiyang Gou0fdf11e2021-04-06 15:15:37 -0700188 comp_if: "if" `or_test` [`comp_iter`]
Georg Brandl96593ed2007-09-07 14:15:41 +0000189
190The comprehension consists of a single expression followed by at least one
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200191:keyword:`!for` clause and zero or more :keyword:`!for` or :keyword:`!if` clauses.
Georg Brandl96593ed2007-09-07 14:15:41 +0000192In this case, the elements of the new container are those that would be produced
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200193by considering each of the :keyword:`!for` or :keyword:`!if` clauses a block,
Georg Brandl96593ed2007-09-07 14:15:41 +0000194nesting from left to right, and evaluating the expression to produce an element
195each time the innermost block is reached.
196
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200197However, aside from the iterable expression in the leftmost :keyword:`!for` clause,
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200198the comprehension is executed in a separate implicitly nested scope. This ensures
199that names assigned to in the target list don't "leak" into the enclosing scope.
200
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200201The iterable expression in the leftmost :keyword:`!for` clause is evaluated
Johnny Gérard4ef9b8e2019-05-13 05:39:32 +0200202directly in the enclosing scope and then passed as an argument to the implicitly
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200203nested scope. Subsequent :keyword:`!for` clauses and any filter condition in the
204leftmost :keyword:`!for` clause cannot be evaluated in the enclosing scope as
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200205they may depend on the values obtained from the leftmost iterable. For example:
206``[x*y for x in range(10) for y in range(x, x+10)]``.
207
208To ensure the comprehension always results in a container of the appropriate
209type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200210nested scope.
Georg Brandl02c30562007-09-07 17:52:53 +0000211
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300212.. index::
213 single: await; in comprehensions
214
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200215Since Python 3.6, in an :keyword:`async def` function, an :keyword:`!async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500216clause may be used to iterate over a :term:`asynchronous iterator`.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200217A comprehension in an :keyword:`!async def` function may consist of either a
218:keyword:`!for` or :keyword:`!async for` clause following the leading
219expression, may contain additional :keyword:`!for` or :keyword:`!async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500220clauses, and may also use :keyword:`await` expressions.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200221If a comprehension contains either :keyword:`!async for` clauses
222or :keyword:`!await` expressions it is called an
Yury Selivanov03660042016-12-15 17:36:05 -0500223:dfn:`asynchronous comprehension`. An asynchronous comprehension may
224suspend the execution of the coroutine function in which it appears.
225See also :pep:`530`.
Georg Brandl96593ed2007-09-07 14:15:41 +0000226
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200227.. versionadded:: 3.6
228 Asynchronous comprehensions were introduced.
229
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200230.. versionchanged:: 3.8
231 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200232
233
Georg Brandl116aa622007-08-15 14:28:22 +0000234.. _lists:
235
236List displays
237-------------
238
239.. index::
240 pair: list; display
241 pair: list; comprehensions
Georg Brandl96593ed2007-09-07 14:15:41 +0000242 pair: empty; list
243 object: list
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200244 single: [] (square brackets); list expression
245 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247A list display is a possibly empty series of expressions enclosed in square
248brackets:
249
Victor Stinner8af239e2020-09-18 09:10:15 +0200250.. productionlist:: python-grammar
Martin Panter0c0da482016-06-12 01:46:50 +0000251 list_display: "[" [`starred_list` | `comprehension`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000252
Georg Brandl96593ed2007-09-07 14:15:41 +0000253A list display yields a new list object, the contents being specified by either
254a list of expressions or a comprehension. When a comma-separated list of
255expressions is supplied, its elements are evaluated from left to right and
256placed into the list object in that order. When a comprehension is supplied,
257the list is constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000258
259
Georg Brandl96593ed2007-09-07 14:15:41 +0000260.. _set:
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Georg Brandl96593ed2007-09-07 14:15:41 +0000262Set displays
263------------
Georg Brandl116aa622007-08-15 14:28:22 +0000264
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300265.. index::
266 pair: set; display
Florian Dahlitz2d55aa92020-10-20 23:27:07 +0200267 pair: set; comprehensions
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300268 object: set
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200269 single: {} (curly brackets); set expression
270 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000271
Georg Brandl96593ed2007-09-07 14:15:41 +0000272A set display is denoted by curly braces and distinguishable from dictionary
273displays by the lack of colons separating keys and values:
Georg Brandl116aa622007-08-15 14:28:22 +0000274
Victor Stinner8af239e2020-09-18 09:10:15 +0200275.. productionlist:: python-grammar
Martin Panter0c0da482016-06-12 01:46:50 +0000276 set_display: "{" (`starred_list` | `comprehension`) "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000277
Georg Brandl96593ed2007-09-07 14:15:41 +0000278A set display yields a new mutable set object, the contents being specified by
279either a sequence of expressions or a comprehension. When a comma-separated
280list of expressions is supplied, its elements are evaluated from left to right
281and added to the set object. When a comprehension is supplied, the set is
282constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Georg Brandl528cdb12008-09-21 07:09:51 +0000284An empty set cannot be constructed with ``{}``; this literal constructs an empty
285dictionary.
Christian Heimes78644762008-03-04 23:39:23 +0000286
287
Georg Brandl116aa622007-08-15 14:28:22 +0000288.. _dict:
289
290Dictionary displays
291-------------------
292
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300293.. index::
294 pair: dictionary; display
Florian Dahlitz2d55aa92020-10-20 23:27:07 +0200295 pair: dictionary; comprehensions
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300296 key, datum, key/datum pair
297 object: dictionary
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200298 single: {} (curly brackets); dictionary expression
299 single: : (colon); in dictionary expressions
300 single: , (comma); in dictionary displays
Georg Brandl116aa622007-08-15 14:28:22 +0000301
302A dictionary display is a possibly empty series of key/datum pairs enclosed in
303curly braces:
304
Victor Stinner8af239e2020-09-18 09:10:15 +0200305.. productionlist:: python-grammar
Georg Brandl96593ed2007-09-07 14:15:41 +0000306 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000307 key_datum_list: `key_datum` ("," `key_datum`)* [","]
Martin Panter0c0da482016-06-12 01:46:50 +0000308 key_datum: `expression` ":" `expression` | "**" `or_expr`
Georg Brandl96593ed2007-09-07 14:15:41 +0000309 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311A dictionary display yields a new dictionary object.
312
Georg Brandl96593ed2007-09-07 14:15:41 +0000313If a comma-separated sequence of key/datum pairs is given, they are evaluated
314from left to right to define the entries of the dictionary: each key object is
315used as a key into the dictionary to store the corresponding datum. This means
316that you can specify the same key multiple times in the key/datum list, and the
317final dictionary's value for that key will be the last one given.
318
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300319.. index::
320 unpacking; dictionary
321 single: **; in dictionary displays
Martin Panter0c0da482016-06-12 01:46:50 +0000322
323A double asterisk ``**`` denotes :dfn:`dictionary unpacking`.
324Its operand must be a :term:`mapping`. Each mapping item is added
325to the new dictionary. Later values replace values already set by
326earlier key/datum pairs and earlier dictionary unpackings.
327
328.. versionadded:: 3.5
329 Unpacking into dictionary displays, originally proposed by :pep:`448`.
330
Georg Brandl96593ed2007-09-07 14:15:41 +0000331A dict comprehension, in contrast to list and set comprehensions, needs two
332expressions separated with a colon followed by the usual "for" and "if" clauses.
333When the comprehension is run, the resulting key and value elements are inserted
334in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000337 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000338
339Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000340:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000341all mutable objects.) Clashes between duplicate keys are not detected; the last
342datum (textually rightmost in the display) stored for a given key value
343prevails.
344
Jörn Heisslerc8a35412019-06-22 16:40:55 +0200345.. versionchanged:: 3.8
346 Prior to Python 3.8, in dict comprehensions, the evaluation order of key
347 and value was not well-defined. In CPython, the value was evaluated before
348 the key. Starting with 3.8, the key is evaluated before the value, as
349 proposed by :pep:`572`.
350
Georg Brandl116aa622007-08-15 14:28:22 +0000351
Georg Brandl96593ed2007-09-07 14:15:41 +0000352.. _genexpr:
353
354Generator expressions
355---------------------
356
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300357.. index::
358 pair: generator; expression
359 object: generator
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200360 single: () (parentheses); generator expression
Georg Brandl96593ed2007-09-07 14:15:41 +0000361
362A generator expression is a compact generator notation in parentheses:
363
Victor Stinner8af239e2020-09-18 09:10:15 +0200364.. productionlist:: python-grammar
Georg Brandl96593ed2007-09-07 14:15:41 +0000365 generator_expression: "(" `expression` `comp_for` ")"
366
367A generator expression yields a new generator object. Its syntax is the same as
368for comprehensions, except that it is enclosed in parentheses instead of
369brackets or curly braces.
370
371Variables used in the generator expression are evaluated lazily when the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700372:meth:`~generator.__next__` method is called for the generator object (in the same
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200373fashion as normal generators). However, the iterable expression in the
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200374leftmost :keyword:`!for` clause is immediately evaluated, so that an error
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200375produced by it will be emitted at the point where the generator expression
376is defined, rather than at the point where the first value is retrieved.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200377Subsequent :keyword:`!for` clauses and any filter condition in the leftmost
378:keyword:`!for` clause cannot be evaluated in the enclosing scope as they may
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200379depend on the values obtained from the leftmost iterable. For example:
380``(x*y for x in range(10) for y in range(x, x+10))``.
Georg Brandl96593ed2007-09-07 14:15:41 +0000381
382The parentheses can be omitted on calls with only one argument. See section
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700383:ref:`calls` for details.
Georg Brandl96593ed2007-09-07 14:15:41 +0000384
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200385To avoid interfering with the expected operation of the generator expression
386itself, ``yield`` and ``yield from`` expressions are prohibited in the
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200387implicitly defined generator.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200388
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200389If a generator expression contains either :keyword:`!async for`
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400390clauses or :keyword:`await` expressions it is called an
391:dfn:`asynchronous generator expression`. An asynchronous generator
392expression returns a new asynchronous generator object,
393which is an asynchronous iterator (see :ref:`async-iterators`).
394
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200395.. versionadded:: 3.6
396 Asynchronous generator expressions were introduced.
397
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400398.. versionchanged:: 3.7
399 Prior to Python 3.7, asynchronous generator expressions could
400 only appear in :keyword:`async def` coroutines. Starting
401 with 3.7, any function can use asynchronous generator expressions.
Georg Brandl96593ed2007-09-07 14:15:41 +0000402
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200403.. versionchanged:: 3.8
404 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200405
406
Georg Brandl116aa622007-08-15 14:28:22 +0000407.. _yieldexpr:
408
409Yield expressions
410-----------------
411
412.. index::
413 keyword: yield
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300414 keyword: from
Georg Brandl116aa622007-08-15 14:28:22 +0000415 pair: yield; expression
416 pair: generator; function
417
Victor Stinner8af239e2020-09-18 09:10:15 +0200418.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000419 yield_atom: "(" `yield_expression` ")"
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000420 yield_expression: "yield" [`expression_list` | "from" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000421
Yury Selivanov03660042016-12-15 17:36:05 -0500422The yield expression is used when defining a :term:`generator` function
423or an :term:`asynchronous generator` function and
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500424thus can only be used in the body of a function definition. Using a yield
Yury Selivanov03660042016-12-15 17:36:05 -0500425expression in a function's body causes that function to be a generator,
426and using it in an :keyword:`async def` function's body causes that
427coroutine function to be an asynchronous generator. For example::
428
429 def gen(): # defines a generator function
430 yield 123
431
Andrés Delfinobfe18392018-11-07 15:12:12 -0300432 async def agen(): # defines an asynchronous generator function
Yury Selivanov03660042016-12-15 17:36:05 -0500433 yield 123
434
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200435Due to their side effects on the containing scope, ``yield`` expressions
436are not permitted as part of the implicitly defined scopes used to
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200437implement comprehensions and generator expressions.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200438
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200439.. versionchanged:: 3.8
440 Yield expressions prohibited in the implicitly nested scopes used to
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200441 implement comprehensions and generator expressions.
442
Yury Selivanov03660042016-12-15 17:36:05 -0500443Generator functions are described below, while asynchronous generator
444functions are described separately in section
445:ref:`asynchronous-generator-functions`.
Georg Brandl116aa622007-08-15 14:28:22 +0000446
447When a generator function is called, it returns an iterator known as a
Guido van Rossumd0150ad2015-05-05 12:02:01 -0700448generator. That generator then controls the execution of the generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000449The execution starts when one of the generator's methods is called. At that
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500450time, the execution proceeds to the first yield expression, where it is
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700451suspended again, returning the value of :token:`expression_list` to the generator's
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500452caller. By suspended, we mean that all local state is retained, including the
Ethan Furman2f825af2015-01-14 22:25:27 -0800453current bindings of local variables, the instruction pointer, the internal
454evaluation stack, and the state of any exception handling. When the execution
455is resumed by calling one of the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500456generator's methods, the function can proceed exactly as if the yield expression
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700457were just another external call. The value of the yield expression after
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500458resuming depends on the method which resumed the execution. If
459:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or
460the :func:`next` builtin) then the result is :const:`None`. Otherwise, if
461:meth:`~generator.send` is used, then the result will be the value passed in to
462that method.
Georg Brandl116aa622007-08-15 14:28:22 +0000463
464.. index:: single: coroutine
465
466All of this makes generator functions quite similar to coroutines; they yield
467multiple times, they have more than one entry point and their execution can be
468suspended. The only difference is that a generator function cannot control
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700469where the execution should continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000470transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000471
Ethan Furman2f825af2015-01-14 22:25:27 -0800472Yield expressions are allowed anywhere in a :keyword:`try` construct. If the
473generator is not resumed before it is
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500474finalized (by reaching a zero reference count or by being garbage collected),
475the generator-iterator's :meth:`~generator.close` method will be called,
476allowing any pending :keyword:`finally` clauses to execute.
Georg Brandl02c30562007-09-07 17:52:53 +0000477
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300478.. index::
479 single: from; yield from expression
480
Terry Jan Reedy2f9ef512021-02-20 21:33:25 -0500481When ``yield from <expr>`` is used, the supplied expression must be an
482iterable. The values produced by iterating that iterable are passed directly
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000483to the caller of the current generator's methods. Any values passed in with
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300484:meth:`~generator.send` and any exceptions passed in with
485:meth:`~generator.throw` are passed to the underlying iterator if it has the
486appropriate methods. If this is not the case, then :meth:`~generator.send`
487will raise :exc:`AttributeError` or :exc:`TypeError`, while
488:meth:`~generator.throw` will just raise the passed in exception immediately.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000489
490When the underlying iterator is complete, the :attr:`~StopIteration.value`
491attribute of the raised :exc:`StopIteration` instance becomes the value of
492the yield expression. It can be either set explicitly when raising
divyag9778a9102019-05-13 08:05:20 -0500493:exc:`StopIteration`, or automatically when the subiterator is a generator
494(by returning a value from the subgenerator).
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000495
Nick Coghlan0ed80192012-01-14 14:43:24 +1000496 .. versionchanged:: 3.3
Martin Panterd21e0b52015-10-10 10:36:22 +0000497 Added ``yield from <expr>`` to delegate control flow to a subiterator.
Nick Coghlan0ed80192012-01-14 14:43:24 +1000498
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500499The parentheses may be omitted when the yield expression is the sole expression
500on the right hand side of an assignment statement.
501
502.. seealso::
503
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300504 :pep:`255` - Simple Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500505 The proposal for adding generators and the :keyword:`yield` statement to Python.
506
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300507 :pep:`342` - Coroutines via Enhanced Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500508 The proposal to enhance the API and syntax of generators, making them
509 usable as simple coroutines.
510
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300511 :pep:`380` - Syntax for Delegating to a Subgenerator
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500512 The proposal to introduce the :token:`yield_from` syntax, making delegation
divyag9778a9102019-05-13 08:05:20 -0500513 to subgenerators easy.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000514
Andrés Delfinobfe18392018-11-07 15:12:12 -0300515 :pep:`525` - Asynchronous Generators
516 The proposal that expanded on :pep:`492` by adding generator capabilities to
517 coroutine functions.
518
Georg Brandl116aa622007-08-15 14:28:22 +0000519.. index:: object: generator
Yury Selivanov66f88282015-06-24 11:04:15 -0400520.. _generator-methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000521
R David Murray2c1d1d62012-08-17 20:48:59 -0400522Generator-iterator methods
523^^^^^^^^^^^^^^^^^^^^^^^^^^
524
525This subsection describes the methods of a generator iterator. They can
526be used to control the execution of a generator function.
527
528Note that calling any of the generator methods below when the generator
529is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000530
531.. index:: exception: StopIteration
532
533
Georg Brandl96593ed2007-09-07 14:15:41 +0000534.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000535
Georg Brandl96593ed2007-09-07 14:15:41 +0000536 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500537 executed yield expression. When a generator function is resumed with a
538 :meth:`~generator.__next__` method, the current yield expression always
539 evaluates to :const:`None`. The execution then continues to the next yield
540 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300541 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500542 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000543 exception is raised.
544
545 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
546 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000547
548
549.. method:: generator.send(value)
550
551 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500552 *value* argument becomes the result of the current yield expression. The
553 :meth:`send` method returns the next value yielded by the generator, or
554 raises :exc:`StopIteration` if the generator exits without yielding another
555 value. When :meth:`send` is called to start the generator, it must be called
556 with :const:`None` as the argument, because there is no yield expression that
557 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000558
559
560.. method:: generator.throw(type[, value[, traceback]])
561
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700562 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000563 and returns the next value yielded by the generator function. If the generator
564 exits without yielding another value, a :exc:`StopIteration` exception is
565 raised. If the generator function does not catch the passed-in exception, or
566 raises a different exception, then that exception propagates to the caller.
567
568.. index:: exception: GeneratorExit
569
570
571.. method:: generator.close()
572
573 Raises a :exc:`GeneratorExit` at the point where the generator function was
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400574 paused. If the generator function then exits gracefully, is already closed,
575 or raises :exc:`GeneratorExit` (by not catching the exception), close
576 returns to its caller. If the generator yields a value, a
577 :exc:`RuntimeError` is raised. If the generator raises any other exception,
578 it is propagated to the caller. :meth:`close` does nothing if the generator
579 has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000580
Chris Jerdonek2654b862012-12-23 15:31:57 -0800581.. index:: single: yield; examples
582
583Examples
584^^^^^^^^
585
Georg Brandl116aa622007-08-15 14:28:22 +0000586Here is a simple example that demonstrates the behavior of generators and
587generator functions::
588
589 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000590 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000591 ... try:
592 ... while True:
593 ... try:
594 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000595 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000596 ... value = e
597 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000598 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000599 ...
600 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000601 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000602 Execution starts when 'next()' is called for the first time.
603 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000604 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000605 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000606 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000607 2
608 >>> generator.throw(TypeError, "spam")
609 TypeError('spam',)
610 >>> generator.close()
611 Don't forget to clean up when 'close()' is called.
612
Chris Jerdonek2654b862012-12-23 15:31:57 -0800613For examples using ``yield from``, see :ref:`pep-380` in "What's New in
614Python."
615
Yury Selivanov03660042016-12-15 17:36:05 -0500616.. _asynchronous-generator-functions:
617
618Asynchronous generator functions
619^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
620
621The presence of a yield expression in a function or method defined using
divyag9778a9102019-05-13 08:05:20 -0500622:keyword:`async def` further defines the function as an
Yury Selivanov03660042016-12-15 17:36:05 -0500623:term:`asynchronous generator` function.
624
625When an asynchronous generator function is called, it returns an
626asynchronous iterator known as an asynchronous generator object.
627That object then controls the execution of the generator function.
628An asynchronous generator object is typically used in an
629:keyword:`async for` statement in a coroutine function analogously to
630how a generator object would be used in a :keyword:`for` statement.
631
632Calling one of the asynchronous generator's methods returns an
633:term:`awaitable` object, and the execution starts when this object
634is awaited on. At that time, the execution proceeds to the first yield
635expression, where it is suspended again, returning the value of
636:token:`expression_list` to the awaiting coroutine. As with a generator,
637suspension means that all local state is retained, including the
638current bindings of local variables, the instruction pointer, the internal
639evaluation stack, and the state of any exception handling. When the execution
640is resumed by awaiting on the next object returned by the asynchronous
641generator's methods, the function can proceed exactly as if the yield
642expression were just another external call. The value of the yield expression
643after resuming depends on the method which resumed the execution. If
644:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
645:meth:`~agen.asend` is used, then the result will be the value passed in to
646that method.
647
Joongi Kim6e8dcda2020-11-02 17:02:48 +0900648If an asynchronous generator happens to exit early by :keyword:`break`, the caller
649task being cancelled, or other exceptions, the generator's async cleanup code
650will run and possibly raise exceptions or access context variables in an
651unexpected context--perhaps after the lifetime of tasks it depends, or
652during the event loop shutdown when the async-generator garbage collection hook
653is called.
654To prevent this, the caller must explicitly close the async generator by calling
655:meth:`~agen.aclose` method to finalize the generator and ultimately detach it
656from the event loop.
657
Yury Selivanov03660042016-12-15 17:36:05 -0500658In an asynchronous generator function, yield expressions are allowed anywhere
659in a :keyword:`try` construct. However, if an asynchronous generator is not
660resumed before it is finalized (by reaching a zero reference count or by
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200661being garbage collected), then a yield expression within a :keyword:`!try`
Yury Selivanov03660042016-12-15 17:36:05 -0500662construct could result in a failure to execute pending :keyword:`finally`
663clauses. In this case, it is the responsibility of the event loop or
664scheduler running the asynchronous generator to call the asynchronous
665generator-iterator's :meth:`~agen.aclose` method and run the resulting
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200666coroutine object, thus allowing any pending :keyword:`!finally` clauses
Yury Selivanov03660042016-12-15 17:36:05 -0500667to execute.
668
Joongi Kim6e8dcda2020-11-02 17:02:48 +0900669To take care of finalization upon event loop termination, an event loop should
670define a *finalizer* function which takes an asynchronous generator-iterator and
671presumably calls :meth:`~agen.aclose` and executes the coroutine.
Yury Selivanov03660042016-12-15 17:36:05 -0500672This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`.
673When first iterated over, an asynchronous generator-iterator will store the
674registered *finalizer* to be called upon finalization. For a reference example
675of a *finalizer* method see the implementation of
676``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`.
677
678The expression ``yield from <expr>`` is a syntax error when used in an
679asynchronous generator function.
680
681.. index:: object: asynchronous-generator
682.. _asynchronous-generator-methods:
683
684Asynchronous generator-iterator methods
685^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
686
687This subsection describes the methods of an asynchronous generator iterator,
688which are used to control the execution of a generator function.
689
690
691.. index:: exception: StopAsyncIteration
692
693.. coroutinemethod:: agen.__anext__()
694
695 Returns an awaitable which when run starts to execute the asynchronous
696 generator or resumes it at the last executed yield expression. When an
divyag9778a9102019-05-13 08:05:20 -0500697 asynchronous generator function is resumed with an :meth:`~agen.__anext__`
Yury Selivanov03660042016-12-15 17:36:05 -0500698 method, the current yield expression always evaluates to :const:`None` in
699 the returned awaitable, which when run will continue to the next yield
700 expression. The value of the :token:`expression_list` of the yield
701 expression is the value of the :exc:`StopIteration` exception raised by
702 the completing coroutine. If the asynchronous generator exits without
divyag9778a9102019-05-13 08:05:20 -0500703 yielding another value, the awaitable instead raises a
Yury Selivanov03660042016-12-15 17:36:05 -0500704 :exc:`StopAsyncIteration` exception, signalling that the asynchronous
705 iteration has completed.
706
707 This method is normally called implicitly by a :keyword:`async for` loop.
708
709
710.. coroutinemethod:: agen.asend(value)
711
712 Returns an awaitable which when run resumes the execution of the
713 asynchronous generator. As with the :meth:`~generator.send()` method for a
714 generator, this "sends" a value into the asynchronous generator function,
715 and the *value* argument becomes the result of the current yield expression.
716 The awaitable returned by the :meth:`asend` method will return the next
717 value yielded by the generator as the value of the raised
718 :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the
719 asynchronous generator exits without yielding another value. When
720 :meth:`asend` is called to start the asynchronous
721 generator, it must be called with :const:`None` as the argument,
722 because there is no yield expression that could receive the value.
723
724
725.. coroutinemethod:: agen.athrow(type[, value[, traceback]])
726
727 Returns an awaitable that raises an exception of type ``type`` at the point
728 where the asynchronous generator was paused, and returns the next value
729 yielded by the generator function as the value of the raised
730 :exc:`StopIteration` exception. If the asynchronous generator exits
divyag9778a9102019-05-13 08:05:20 -0500731 without yielding another value, a :exc:`StopAsyncIteration` exception is
Yury Selivanov03660042016-12-15 17:36:05 -0500732 raised by the awaitable.
733 If the generator function does not catch the passed-in exception, or
delirious-lettuce3378b202017-05-19 14:37:57 -0600734 raises a different exception, then when the awaitable is run that exception
Yury Selivanov03660042016-12-15 17:36:05 -0500735 propagates to the caller of the awaitable.
736
737.. index:: exception: GeneratorExit
738
739
740.. coroutinemethod:: agen.aclose()
741
742 Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
743 the asynchronous generator function at the point where it was paused.
744 If the asynchronous generator function then exits gracefully, is already
745 closed, or raises :exc:`GeneratorExit` (by not catching the exception),
746 then the returned awaitable will raise a :exc:`StopIteration` exception.
747 Any further awaitables returned by subsequent calls to the asynchronous
748 generator will raise a :exc:`StopAsyncIteration` exception. If the
749 asynchronous generator yields a value, a :exc:`RuntimeError` is raised
750 by the awaitable. If the asynchronous generator raises any other exception,
751 it is propagated to the caller of the awaitable. If the asynchronous
752 generator has already exited due to an exception or normal exit, then
753 further calls to :meth:`aclose` will return an awaitable that does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000754
Georg Brandl116aa622007-08-15 14:28:22 +0000755.. _primaries:
756
757Primaries
758=========
759
760.. index:: single: primary
761
762Primaries represent the most tightly bound operations of the language. Their
763syntax is:
764
Victor Stinner8af239e2020-09-18 09:10:15 +0200765.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000766 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
767
768
769.. _attribute-references:
770
771Attribute references
772--------------------
773
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300774.. index::
775 pair: attribute; reference
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200776 single: . (dot); attribute reference
Georg Brandl116aa622007-08-15 14:28:22 +0000777
778An attribute reference is a primary followed by a period and a name:
779
Victor Stinner8af239e2020-09-18 09:10:15 +0200780.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000781 attributeref: `primary` "." `identifier`
782
783.. index::
784 exception: AttributeError
785 object: module
786 object: list
787
788The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000789references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700790attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500791overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700792the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
793the object produced is determined by the object. Multiple evaluations of the
794same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000795
796
797.. _subscriptions:
798
799Subscriptions
800-------------
801
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300802.. index::
803 single: subscription
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200804 single: [] (square brackets); subscription
Georg Brandl116aa622007-08-15 14:28:22 +0000805
806.. index::
807 object: sequence
808 object: mapping
809 object: string
810 object: tuple
811 object: list
812 object: dictionary
813 pair: sequence; item
814
kj7cdf30f2020-10-21 07:38:08 +0800815Subscription of a sequence (string, tuple or list) or mapping (dictionary)
816object usually selects an item from the collection:
Georg Brandl116aa622007-08-15 14:28:22 +0000817
Victor Stinner8af239e2020-09-18 09:10:15 +0200818.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000819 subscription: `primary` "[" `expression_list` "]"
820
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700821The primary must evaluate to an object that supports subscription (lists or
822dictionaries for example). User-defined objects can support subscription by
823defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000824
825For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000826
827If the primary is a mapping, the expression list must evaluate to an object
828whose value is one of the keys of the mapping, and the subscription selects the
829value in the mapping that corresponds to that key. (The expression list is a
830tuple except if it has exactly one item.)
831
Andrés Delfino4fddd4e2018-06-15 15:24:25 -0300832If the primary is a sequence, the expression list must evaluate to an integer
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000833or a slice (as discussed in the following section).
834
835The formal syntax makes no special provision for negative indices in
836sequences; however, built-in sequences all provide a :meth:`__getitem__`
837method that interprets negative indices by adding the length of the sequence
838to the index (so that ``x[-1]`` selects the last item of ``x``). The
839resulting value must be a nonnegative integer less than the number of items in
840the sequence, and the subscription selects the item whose index is that value
841(counting from zero). Since the support for negative indices and slicing
842occurs in the object's :meth:`__getitem__` method, subclasses overriding
843this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000844
845.. index::
846 single: character
847 pair: string; item
848
849A string's items are characters. A character is not a separate data type but a
850string of exactly one character.
851
kj7cdf30f2020-10-21 07:38:08 +0800852Subscription of certain :term:`classes <class>` or :term:`types <type>`
kj9129af62020-10-30 12:01:17 +0800853creates a :ref:`generic alias <types-genericalias>`.
kj7cdf30f2020-10-21 07:38:08 +0800854In this case, user-defined classes can support subscription by providing a
855:meth:`__class_getitem__` classmethod.
856
Georg Brandl116aa622007-08-15 14:28:22 +0000857
858.. _slicings:
859
860Slicings
861--------
862
863.. index::
864 single: slicing
865 single: slice
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200866 single: : (colon); slicing
867 single: , (comma); slicing
Georg Brandl116aa622007-08-15 14:28:22 +0000868
869.. index::
870 object: sequence
871 object: string
872 object: tuple
873 object: list
874
875A slicing selects a range of items in a sequence object (e.g., a string, tuple
876or list). Slicings may be used as expressions or as targets in assignment or
877:keyword:`del` statements. The syntax for a slicing:
878
Victor Stinner8af239e2020-09-18 09:10:15 +0200879.. productionlist:: python-grammar
Georg Brandl48310cd2009-01-03 21:18:54 +0000880 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000881 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000882 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000883 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000884 lower_bound: `expression`
885 upper_bound: `expression`
886 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000887
888There is ambiguity in the formal syntax here: anything that looks like an
889expression list also looks like a slice list, so any subscription can be
890interpreted as a slicing. Rather than further complicating the syntax, this is
891disambiguated by defining that in this case the interpretation as a subscription
892takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000893slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000894
895.. index::
896 single: start (slice object attribute)
897 single: stop (slice object attribute)
898 single: step (slice object attribute)
899
Georg Brandla4c8c472014-10-31 10:38:49 +0100900The semantics for a slicing are as follows. The primary is indexed (using the
901same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000902normal subscription) with a key that is constructed from the slice list, as
903follows. If the slice list contains at least one comma, the key is a tuple
904containing the conversion of the slice items; otherwise, the conversion of the
905lone slice item is the key. The conversion of a slice item that is an
906expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300907object (see section :ref:`types`) whose :attr:`~slice.start`,
908:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
909expressions given as lower bound, upper bound and stride, respectively,
910substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000911
912
Chris Jerdonekb4309942012-12-25 14:54:44 -0800913.. index::
914 object: callable
915 single: call
916 single: argument; call semantics
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200917 single: () (parentheses); call
918 single: , (comma); argument list
919 single: = (equals); in function calls
Chris Jerdonekb4309942012-12-25 14:54:44 -0800920
Georg Brandl116aa622007-08-15 14:28:22 +0000921.. _calls:
922
923Calls
924-----
925
Chris Jerdonekb4309942012-12-25 14:54:44 -0800926A call calls a callable object (e.g., a :term:`function`) with a possibly empty
927series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000928
Victor Stinner8af239e2020-09-18 09:10:15 +0200929.. productionlist:: python-grammar
Georg Brandldc529c12008-09-21 17:03:29 +0000930 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Martin Panter0c0da482016-06-12 01:46:50 +0000931 argument_list: `positional_arguments` ["," `starred_and_keywords`]
932 : ["," `keywords_arguments`]
933 : | `starred_and_keywords` ["," `keywords_arguments`]
934 : | `keywords_arguments`
Brandt Bucher8bae2192020-03-05 21:19:22 -0800935 positional_arguments: positional_item ("," positional_item)*
936 positional_item: `assignment_expression` | "*" `expression`
Martin Panter0c0da482016-06-12 01:46:50 +0000937 starred_and_keywords: ("*" `expression` | `keyword_item`)
938 : ("," "*" `expression` | "," `keyword_item`)*
939 keywords_arguments: (`keyword_item` | "**" `expression`)
Martin Panter7106a512016-12-24 10:20:38 +0000940 : ("," `keyword_item` | "," "**" `expression`)*
Georg Brandl116aa622007-08-15 14:28:22 +0000941 keyword_item: `identifier` "=" `expression`
942
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700943An optional trailing comma may be present after the positional and keyword arguments
944but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000945
Chris Jerdonekb4309942012-12-25 14:54:44 -0800946.. index::
947 single: parameter; call semantics
948
Georg Brandl116aa622007-08-15 14:28:22 +0000949The primary must evaluate to a callable object (user-defined functions, built-in
950functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000951instances, and all objects having a :meth:`__call__` method are callable). All
952argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800953to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000954
955.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000956
957If keyword arguments are present, they are first converted to positional
958arguments, as follows. First, a list of unfilled slots is created for the
959formal parameters. If there are N positional arguments, they are placed in the
960first N slots. Next, for each keyword argument, the identifier is used to
961determine the corresponding slot (if the identifier is the same as the first
962formal parameter name, the first slot is used, and so on). If the slot is
963already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
964the argument is placed in the slot, filling it (even if the expression is
965``None``, it fills the slot). When all arguments have been processed, the slots
966that are still unfilled are filled with the corresponding default value from the
967function definition. (Default values are calculated, once, when the function is
968defined; thus, a mutable object such as a list or dictionary used as default
969value will be shared by all calls that don't specify an argument value for the
970corresponding slot; this should usually be avoided.) If there are any unfilled
971slots for which no default value is specified, a :exc:`TypeError` exception is
972raised. Otherwise, the list of filled slots is used as the argument list for
973the call.
974
Georg Brandl495f7b52009-10-27 15:28:25 +0000975.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000976
Georg Brandl495f7b52009-10-27 15:28:25 +0000977 An implementation may provide built-in functions whose positional parameters
978 do not have names, even if they are 'named' for the purpose of documentation,
979 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000980 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000981 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000982
Georg Brandl116aa622007-08-15 14:28:22 +0000983If there are more positional arguments than there are formal parameter slots, a
984:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
985``*identifier`` is present; in this case, that formal parameter receives a tuple
986containing the excess positional arguments (or an empty tuple if there were no
987excess positional arguments).
988
989If any keyword argument does not correspond to a formal parameter name, a
990:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
991``**identifier`` is present; in this case, that formal parameter receives a
992dictionary containing the excess keyword arguments (using the keywords as keys
993and the argument values as corresponding values), or a (new) empty dictionary if
994there were no excess keyword arguments.
995
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300996.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200997 single: * (asterisk); in function calls
Martin Panter0c0da482016-06-12 01:46:50 +0000998 single: unpacking; in function calls
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300999
Georg Brandl116aa622007-08-15 14:28:22 +00001000If the syntax ``*expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +00001001evaluate to an :term:`iterable`. Elements from these iterables are
1002treated as if they were additional positional arguments. For the call
1003``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*,
1004this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
1005*y1*, ..., *yM*, *x3*, *x4*.
Georg Brandl116aa622007-08-15 14:28:22 +00001006
Benjamin Peterson2d735bc2008-08-19 20:57:10 +00001007A consequence of this is that although the ``*expression`` syntax may appear
Martin Panter0c0da482016-06-12 01:46:50 +00001008*after* explicit keyword arguments, it is processed *before* the
1009keyword arguments (and any ``**expression`` arguments -- see below). So::
Georg Brandl116aa622007-08-15 14:28:22 +00001010
1011 >>> def f(a, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +03001012 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +00001013 ...
1014 >>> f(b=1, *(2,))
1015 2 1
1016 >>> f(a=1, *(2,))
1017 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +05301018 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +00001019 TypeError: f() got multiple values for keyword argument 'a'
1020 >>> f(1, *(2,))
1021 1 2
1022
1023It is unusual for both keyword arguments and the ``*expression`` syntax to be
1024used in the same call, so in practice this confusion does not arise.
1025
Eli Bendersky7bd081c2011-07-30 07:05:16 +03001026.. index::
1027 single: **; in function calls
1028
Georg Brandl116aa622007-08-15 14:28:22 +00001029If the syntax ``**expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +00001030evaluate to a :term:`mapping`, the contents of which are treated as
1031additional keyword arguments. If a keyword is already present
1032(as an explicit keyword argument, or from another unpacking),
1033a :exc:`TypeError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001034
1035Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
1036used as positional argument slots or as keyword argument names.
1037
Martin Panter0c0da482016-06-12 01:46:50 +00001038.. versionchanged:: 3.5
1039 Function calls accept any number of ``*`` and ``**`` unpackings,
1040 positional arguments may follow iterable unpackings (``*``),
1041 and keyword arguments may follow dictionary unpackings (``**``).
1042 Originally proposed by :pep:`448`.
1043
Georg Brandl116aa622007-08-15 14:28:22 +00001044A call always returns some value, possibly ``None``, unless it raises an
1045exception. How this value is computed depends on the type of the callable
1046object.
1047
1048If it is---
1049
1050a user-defined function:
1051 .. index::
1052 pair: function; call
1053 triple: user-defined; function; call
1054 object: user-defined function
1055 object: function
1056
1057 The code block for the function is executed, passing it the argument list. The
1058 first thing the code block will do is bind the formal parameters to the
1059 arguments; this is described in section :ref:`function`. When the code block
1060 executes a :keyword:`return` statement, this specifies the return value of the
1061 function call.
1062
1063a built-in function or method:
1064 .. index::
1065 pair: function; call
1066 pair: built-in function; call
1067 pair: method; call
1068 pair: built-in method; call
1069 object: built-in method
1070 object: built-in function
1071 object: method
1072 object: function
1073
1074 The result is up to the interpreter; see :ref:`built-in-funcs` for the
1075 descriptions of built-in functions and methods.
1076
1077a class object:
1078 .. index::
1079 object: class
1080 pair: class object; call
1081
1082 A new instance of that class is returned.
1083
1084a class instance method:
1085 .. index::
1086 object: class instance
1087 object: instance
1088 pair: class instance; call
1089
1090 The corresponding user-defined function is called, with an argument list that is
1091 one longer than the argument list of the call: the instance becomes the first
1092 argument.
1093
1094a class instance:
1095 .. index::
1096 pair: instance; call
1097 single: __call__() (object method)
1098
1099 The class must define a :meth:`__call__` method; the effect is then the same as
1100 if that method was called.
1101
1102
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001103.. index:: keyword: await
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001104.. _await:
1105
1106Await expression
1107================
1108
1109Suspend the execution of :term:`coroutine` on an :term:`awaitable` object.
1110Can only be used inside a :term:`coroutine function`.
1111
Victor Stinner8af239e2020-09-18 09:10:15 +02001112.. productionlist:: python-grammar
Serhiy Storchakac7cc9852016-05-08 21:59:46 +03001113 await_expr: "await" `primary`
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001114
1115.. versionadded:: 3.5
1116
1117
Georg Brandl116aa622007-08-15 14:28:22 +00001118.. _power:
1119
1120The power operator
1121==================
1122
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001123.. index::
1124 pair: power; operation
1125 operator: **
1126
Georg Brandl116aa622007-08-15 14:28:22 +00001127The power operator binds more tightly than unary operators on its left; it binds
1128less tightly than unary operators on its right. The syntax is:
1129
Victor Stinner8af239e2020-09-18 09:10:15 +02001130.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001131 power: (`await_expr` | `primary`) ["**" `u_expr`]
Georg Brandl116aa622007-08-15 14:28:22 +00001132
1133Thus, in an unparenthesized sequence of power and unary operators, the operators
1134are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +00001135for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001136
1137The power operator has the same semantics as the built-in :func:`pow` function,
1138when called with two arguments: it yields its left argument raised to the power
1139of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +00001140type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +00001141
Georg Brandl96593ed2007-09-07 14:15:41 +00001142For int operands, the result has the same type as the operands unless the second
1143argument is negative; in that case, all arguments are converted to float and a
1144float result is delivered. For example, ``10**2`` returns ``100``, but
1145``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +00001146
1147Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +00001148Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001149number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001150
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001151This operation can be customized using the special :meth:`__pow__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001152
1153.. _unary:
1154
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001155Unary arithmetic and bitwise operations
1156=======================================
Georg Brandl116aa622007-08-15 14:28:22 +00001157
1158.. index::
1159 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +00001160 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001161
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001162All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +00001163
Victor Stinner8af239e2020-09-18 09:10:15 +02001164.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +00001165 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
1166
1167.. index::
1168 single: negation
1169 single: minus
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001170 single: operator; - (minus)
1171 single: - (minus); unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001172
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001173The unary ``-`` (minus) operator yields the negation of its numeric argument; the
1174operation can be overridden with the :meth:`__neg__` special method.
Georg Brandl116aa622007-08-15 14:28:22 +00001175
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001176.. index::
1177 single: plus
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001178 single: operator; + (plus)
1179 single: + (plus); unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001180
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001181The unary ``+`` (plus) operator yields its numeric argument unchanged; the
1182operation can be overridden with the :meth:`__pos__` special method.
Georg Brandl116aa622007-08-15 14:28:22 +00001183
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001184.. index::
1185 single: inversion
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001186 operator: ~ (tilde)
Christian Heimesfaf2f632008-01-06 16:59:19 +00001187
Georg Brandl95817b32008-05-11 14:30:18 +00001188The unary ``~`` (invert) operator yields the bitwise inversion of its integer
1189argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001190applies to integral numbers or to custom objects that override the
1191:meth:`__invert__` special method.
1192
1193
Georg Brandl116aa622007-08-15 14:28:22 +00001194
1195.. index:: exception: TypeError
1196
1197In all three cases, if the argument does not have the proper type, a
1198:exc:`TypeError` exception is raised.
1199
1200
1201.. _binary:
1202
1203Binary arithmetic operations
1204============================
1205
1206.. index:: triple: binary; arithmetic; operation
1207
1208The binary arithmetic operations have the conventional priority levels. Note
1209that some of these operations also apply to certain non-numeric types. Apart
1210from the power operator, there are only two levels, one for multiplicative
1211operators and one for additive operators:
1212
Victor Stinner8af239e2020-09-18 09:10:15 +02001213.. productionlist:: python-grammar
Benjamin Petersond51374e2014-04-09 23:55:56 -04001214 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
Andrés Delfinocaccca782018-07-07 17:24:46 -03001215 : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` |
Benjamin Petersond51374e2014-04-09 23:55:56 -04001216 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001217 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
1218
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001219.. index::
1220 single: multiplication
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001221 operator: * (asterisk)
Georg Brandl116aa622007-08-15 14:28:22 +00001222
1223The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +00001224arguments must either both be numbers, or one argument must be an integer and
1225the other must be a sequence. In the former case, the numbers are converted to a
1226common type and then multiplied together. In the latter case, sequence
1227repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001228
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001229This operation can be customized using the special :meth:`__mul__` and
1230:meth:`__rmul__` methods.
1231
Andrés Delfino69511862018-06-15 16:23:00 -03001232.. index::
1233 single: matrix multiplication
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001234 operator: @ (at)
Benjamin Petersond51374e2014-04-09 23:55:56 -04001235
1236The ``@`` (at) operator is intended to be used for matrix multiplication. No
1237builtin Python types implement this operator.
1238
1239.. versionadded:: 3.5
1240
Georg Brandl116aa622007-08-15 14:28:22 +00001241.. index::
1242 exception: ZeroDivisionError
1243 single: division
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001244 operator: / (slash)
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001245 operator: //
Georg Brandl116aa622007-08-15 14:28:22 +00001246
1247The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
1248their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +02001249Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +00001250integer; the result is that of mathematical division with the 'floor' function
1251applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
1252exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001253
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001254This operation can be customized using the special :meth:`__div__` and
1255:meth:`__floordiv__` methods.
1256
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001257.. index::
1258 single: modulo
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001259 operator: % (percent)
Georg Brandl116aa622007-08-15 14:28:22 +00001260
1261The ``%`` (modulo) operator yields the remainder from the division of the first
1262argument by the second. The numeric arguments are first converted to a common
1263type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
1264arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
1265(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
1266result with the same sign as its second operand (or zero); the absolute value of
1267the result is strictly smaller than the absolute value of the second operand
1268[#]_.
1269
Georg Brandl96593ed2007-09-07 14:15:41 +00001270The floor division and modulo operators are connected by the following
1271identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
1272connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
1273x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +00001274
1275In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +00001276also overloaded by string objects to perform old-style string formatting (also
1277known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +00001278Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +00001279
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001280The *modulo* operation can be customized using the special :meth:`__mod__` method.
1281
Georg Brandl116aa622007-08-15 14:28:22 +00001282The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +00001283function are not defined for complex numbers. Instead, convert to a floating
1284point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +00001285
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001286.. index::
1287 single: addition
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001288 single: operator; + (plus)
1289 single: + (plus); binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001290
Georg Brandl96593ed2007-09-07 14:15:41 +00001291The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001292must either both be numbers or both be sequences of the same type. In the
1293former case, the numbers are converted to a common type and then added together.
1294In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +00001295
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001296This operation can be customized using the special :meth:`__add__` and
1297:meth:`__radd__` methods.
1298
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001299.. index::
1300 single: subtraction
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001301 single: operator; - (minus)
1302 single: - (minus); binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001303
1304The ``-`` (subtraction) operator yields the difference of its arguments. The
1305numeric arguments are first converted to a common type.
1306
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001307This operation can be customized using the special :meth:`__sub__` method.
1308
Georg Brandl116aa622007-08-15 14:28:22 +00001309
1310.. _shifting:
1311
1312Shifting operations
1313===================
1314
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001315.. index::
1316 pair: shifting; operation
1317 operator: <<
1318 operator: >>
Georg Brandl116aa622007-08-15 14:28:22 +00001319
1320The shifting operations have lower priority than the arithmetic operations:
1321
Victor Stinner8af239e2020-09-18 09:10:15 +02001322.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001323 shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001324
Georg Brandl96593ed2007-09-07 14:15:41 +00001325These operators accept integers as arguments. They shift the first argument to
1326the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001327
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001328This operation can be customized using the special :meth:`__lshift__` and
1329:meth:`__rshift__` methods.
1330
Georg Brandl116aa622007-08-15 14:28:22 +00001331.. index:: exception: ValueError
1332
Georg Brandl0aaae262013-10-08 21:47:18 +02001333A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
1334shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001335
1336
1337.. _bitwise:
1338
Christian Heimesfaf2f632008-01-06 16:59:19 +00001339Binary bitwise operations
1340=========================
Georg Brandl116aa622007-08-15 14:28:22 +00001341
Christian Heimesfaf2f632008-01-06 16:59:19 +00001342.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001343
1344Each of the three bitwise operations has a different priority level:
1345
Victor Stinner8af239e2020-09-18 09:10:15 +02001346.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +00001347 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1348 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1349 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1350
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001351.. index::
1352 pair: bitwise; and
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001353 operator: & (ampersand)
Georg Brandl116aa622007-08-15 14:28:22 +00001354
Georg Brandl96593ed2007-09-07 14:15:41 +00001355The ``&`` operator yields the bitwise AND of its arguments, which must be
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001356integers or one of them must be a custom object overriding :meth:`__and__` or
1357:meth:`__rand__` special methods.
Georg Brandl116aa622007-08-15 14:28:22 +00001358
1359.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001360 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001361 pair: exclusive; or
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001362 operator: ^ (caret)
Georg Brandl116aa622007-08-15 14:28:22 +00001363
1364The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001365must be integers or one of them must be a custom object overriding :meth:`__xor__` or
1366:meth:`__rxor__` special methods.
Georg Brandl116aa622007-08-15 14:28:22 +00001367
1368.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001369 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001370 pair: inclusive; or
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001371 operator: | (vertical bar)
Georg Brandl116aa622007-08-15 14:28:22 +00001372
1373The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001374must be integers or one of them must be a custom object overriding :meth:`__or__` or
1375:meth:`__ror__` special methods.
Georg Brandl116aa622007-08-15 14:28:22 +00001376
1377
1378.. _comparisons:
1379
1380Comparisons
1381===========
1382
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001383.. index::
1384 single: comparison
1385 pair: C; language
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001386 operator: < (less)
1387 operator: > (greater)
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001388 operator: <=
1389 operator: >=
1390 operator: ==
1391 operator: !=
Georg Brandl116aa622007-08-15 14:28:22 +00001392
1393Unlike C, all comparison operations in Python have the same priority, which is
1394lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1395C, expressions like ``a < b < c`` have the interpretation that is conventional
1396in mathematics:
1397
Victor Stinner8af239e2020-09-18 09:10:15 +02001398.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001399 comparison: `or_expr` (`comp_operator` `or_expr`)*
Georg Brandl116aa622007-08-15 14:28:22 +00001400 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1401 : | "is" ["not"] | ["not"] "in"
1402
Miss Islington (bot)843b3d282021-07-30 10:25:45 -07001403Comparisons yield boolean values: ``True`` or ``False``. Custom
1404:dfn:`rich comparison methods` may return non-boolean values. In this case
1405Python will call :func:`bool` on such value in boolean contexts.
Georg Brandl116aa622007-08-15 14:28:22 +00001406
1407.. index:: pair: chaining; comparisons
1408
1409Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1410``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1411cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1412
Guido van Rossum04110fb2007-08-24 16:32:05 +00001413Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1414*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1415to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1416evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001417
Guido van Rossum04110fb2007-08-24 16:32:05 +00001418Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001419*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1420pretty).
1421
Martin Panteraa0da862015-09-23 05:28:13 +00001422Value comparisons
1423-----------------
1424
Georg Brandl116aa622007-08-15 14:28:22 +00001425The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
Martin Panteraa0da862015-09-23 05:28:13 +00001426values of two objects. The objects do not need to have the same type.
Georg Brandl116aa622007-08-15 14:28:22 +00001427
Martin Panteraa0da862015-09-23 05:28:13 +00001428Chapter :ref:`objects` states that objects have a value (in addition to type
1429and identity). The value of an object is a rather abstract notion in Python:
1430For example, there is no canonical access method for an object's value. Also,
1431there is no requirement that the value of an object should be constructed in a
1432particular way, e.g. comprised of all its data attributes. Comparison operators
1433implement a particular notion of what the value of an object is. One can think
1434of them as defining the value of an object indirectly, by means of their
1435comparison implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00001436
Martin Panteraa0da862015-09-23 05:28:13 +00001437Because all types are (direct or indirect) subtypes of :class:`object`, they
1438inherit the default comparison behavior from :class:`object`. Types can
1439customize their comparison behavior by implementing
1440:dfn:`rich comparison methods` like :meth:`__lt__`, described in
1441:ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001442
Martin Panteraa0da862015-09-23 05:28:13 +00001443The default behavior for equality comparison (``==`` and ``!=``) is based on
1444the identity of the objects. Hence, equality comparison of instances with the
1445same identity results in equality, and equality comparison of instances with
1446different identities results in inequality. A motivation for this default
1447behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1448implies ``x == y``).
1449
1450A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1451an attempt raises :exc:`TypeError`. A motivation for this default behavior is
1452the lack of a similar invariant as for equality.
1453
1454The behavior of the default equality comparison, that instances with different
1455identities are always unequal, may be in contrast to what types will need that
1456have a sensible definition of object value and value-based equality. Such
1457types will need to customize their comparison behavior, and in fact, a number
1458of built-in types have done that.
1459
1460The following list describes the comparison behavior of the most important
1461built-in types.
1462
1463* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1464 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
1465 compared within and across their types, with the restriction that complex
1466 numbers do not support order comparison. Within the limits of the types
1467 involved, they compare mathematically (algorithmically) correct without loss
1468 of precision.
1469
Tony Fluryad8a0002018-09-14 18:48:50 +01001470 The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are
1471 special. Any ordered comparison of a number to a not-a-number value is false.
1472 A counter-intuitive implication is that not-a-number values are not equal to
Mark Dickinson810f68f2020-04-05 10:25:24 +01001473 themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3`` and
1474 ``x == x`` are all false, while ``x != x`` is true. This behavior is
1475 compliant with IEEE 754.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001476
Raymond Hettingeredd21122019-08-24 10:43:55 -07001477* ``None`` and ``NotImplemented`` are singletons. :PEP:`8` advises that
1478 comparisons for singletons should always be done with ``is`` or ``is not``,
1479 never the equality operators.
1480
Martin Panteraa0da862015-09-23 05:28:13 +00001481* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
1482 compared within and across their types. They compare lexicographically using
1483 the numeric values of their elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001484
Martin Panteraa0da862015-09-23 05:28:13 +00001485* Strings (instances of :class:`str`) compare lexicographically using the
1486 numerical Unicode code points (the result of the built-in function
1487 :func:`ord`) of their characters. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001488
Martin Panteraa0da862015-09-23 05:28:13 +00001489 Strings and binary sequences cannot be directly compared.
Georg Brandl116aa622007-08-15 14:28:22 +00001490
Martin Panteraa0da862015-09-23 05:28:13 +00001491* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can
1492 be compared only within each of their types, with the restriction that ranges
1493 do not support order comparison. Equality comparison across these types
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +02001494 results in inequality, and ordering comparison across these types raises
Martin Panteraa0da862015-09-23 05:28:13 +00001495 :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001496
Martin Panteraa0da862015-09-23 05:28:13 +00001497 Sequences compare lexicographically using comparison of corresponding
Raymond Hettingeredd21122019-08-24 10:43:55 -07001498 elements. The built-in containers typically assume identical objects are
1499 equal to themselves. That lets them bypass equality tests for identical
1500 objects to improve performance and to maintain their internal invariants.
Martin Panteraa0da862015-09-23 05:28:13 +00001501
1502 Lexicographical comparison between built-in collections works as follows:
1503
1504 - For two collections to compare equal, they must be of the same type, have
1505 the same length, and each pair of corresponding elements must compare
1506 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1507 same).
1508
1509 - Collections that support order comparison are ordered the same as their
1510 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same
1511 value as ``x <= y``). If a corresponding element does not exist, the
1512 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1513 true).
1514
1515* Mappings (instances of :class:`dict`) compare equal if and only if they have
cocoatomocdcac032017-03-31 14:48:49 +09001516 equal `(key, value)` pairs. Equality comparison of the keys and values
Martin Panteraa0da862015-09-23 05:28:13 +00001517 enforces reflexivity.
1518
1519 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
1520
1521* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within
1522 and across their types.
1523
1524 They define order
1525 comparison operators to mean subset and superset tests. Those relations do
1526 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}``
1527 are not equal, nor subsets of one another, nor supersets of one
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001528 another). Accordingly, sets are not appropriate arguments for functions
Martin Panteraa0da862015-09-23 05:28:13 +00001529 which depend on total ordering (for example, :func:`min`, :func:`max`, and
1530 :func:`sorted` produce undefined results given a list of sets as inputs).
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001531
Martin Panteraa0da862015-09-23 05:28:13 +00001532 Comparison of sets enforces reflexivity of its elements.
Georg Brandl116aa622007-08-15 14:28:22 +00001533
Martin Panteraa0da862015-09-23 05:28:13 +00001534* Most other built-in types have no comparison methods implemented, so they
1535 inherit the default comparison behavior.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001536
Martin Panteraa0da862015-09-23 05:28:13 +00001537User-defined classes that customize their comparison behavior should follow
1538some consistency rules, if possible:
1539
1540* Equality comparison should be reflexive.
1541 In other words, identical objects should compare equal:
1542
1543 ``x is y`` implies ``x == y``
1544
1545* Comparison should be symmetric.
1546 In other words, the following expressions should have the same result:
1547
1548 ``x == y`` and ``y == x``
1549
1550 ``x != y`` and ``y != x``
1551
1552 ``x < y`` and ``y > x``
1553
1554 ``x <= y`` and ``y >= x``
1555
1556* Comparison should be transitive.
1557 The following (non-exhaustive) examples illustrate that:
1558
1559 ``x > y and y > z`` implies ``x > z``
1560
1561 ``x < y and y <= z`` implies ``x < z``
1562
1563* Inverse comparison should result in the boolean negation.
1564 In other words, the following expressions should have the same result:
1565
1566 ``x == y`` and ``not x != y``
1567
1568 ``x < y`` and ``not x >= y`` (for total ordering)
1569
1570 ``x > y`` and ``not x <= y`` (for total ordering)
1571
1572 The last two expressions apply to totally ordered collections (e.g. to
1573 sequences, but not to sets or mappings). See also the
1574 :func:`~functools.total_ordering` decorator.
1575
Martin Panter8dbb0ca2017-01-29 10:00:23 +00001576* The :func:`hash` result should be consistent with equality.
1577 Objects that are equal should either have the same hash value,
1578 or be marked as unhashable.
1579
Martin Panteraa0da862015-09-23 05:28:13 +00001580Python does not enforce these consistency rules. In fact, the not-a-number
1581values are an example for not following these rules.
1582
1583
1584.. _in:
1585.. _not in:
Georg Brandl495f7b52009-10-27 15:28:25 +00001586.. _membership-test-details:
1587
Martin Panteraa0da862015-09-23 05:28:13 +00001588Membership test operations
1589--------------------------
1590
Georg Brandl96593ed2007-09-07 14:15:41 +00001591The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301592s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
1593``x not in s`` returns the negation of ``x in s``. All built-in sequences and
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001594set types support this as well as dictionary, for which :keyword:`!in` tests
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301595whether the dictionary has a given key. For container types such as list, tuple,
1596set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001597to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001598
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301599For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
Georg Brandl4b491312007-08-31 09:22:56 +00001600substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1601always considered to be a substring of any other string, so ``"" in "abc"`` will
1602return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001603
Georg Brandl116aa622007-08-15 14:28:22 +00001604For user-defined classes which define the :meth:`__contains__` method, ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301605y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and
1606``False`` otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001607
Georg Brandl495f7b52009-10-27 15:28:25 +00001608For user-defined classes which do not define :meth:`__contains__` but do define
Antti Haapala2f5b9dc2019-05-30 23:19:29 +03001609:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z``, for which the
1610expression ``x is z or x == z`` is true, is produced while iterating over ``y``.
1611If an exception is raised during the iteration, it is as if :keyword:`in` raised
1612that exception.
Georg Brandl495f7b52009-10-27 15:28:25 +00001613
1614Lastly, the old-style iteration protocol is tried: if a class defines
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301615:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
Antti Haapala2f5b9dc2019-05-30 23:19:29 +03001616integer index *i* such that ``x is y[i] or x == y[i]``, and no lower integer index
1617raises the :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001618if :keyword:`in` raised that exception).
1619
1620.. index::
1621 operator: in
1622 operator: not in
1623 pair: membership; test
1624 object: sequence
1625
divyag9778a9102019-05-13 08:05:20 -05001626The operator :keyword:`not in` is defined to have the inverse truth value of
Georg Brandl116aa622007-08-15 14:28:22 +00001627:keyword:`in`.
1628
1629.. index::
1630 operator: is
1631 operator: is not
1632 pair: identity; test
1633
Martin Panteraa0da862015-09-23 05:28:13 +00001634
1635.. _is:
1636.. _is not:
1637
1638Identity comparisons
1639--------------------
1640
divyag9778a9102019-05-13 08:05:20 -05001641The operators :keyword:`is` and :keyword:`is not` test for an object's identity: ``x
1642is 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 -07001643is determined using the :meth:`id` function. ``x is not y`` yields the inverse
1644truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001645
1646
1647.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001648.. _and:
1649.. _or:
1650.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001651
1652Boolean operations
1653==================
1654
1655.. index::
1656 pair: Conditional; expression
1657 pair: Boolean; operation
1658
Victor Stinner8af239e2020-09-18 09:10:15 +02001659.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +00001660 or_test: `and_test` | `or_test` "or" `and_test`
1661 and_test: `not_test` | `and_test` "and" `not_test`
1662 not_test: `comparison` | "not" `not_test`
1663
1664In the context of Boolean operations, and also when expressions are used by
1665control flow statements, the following values are interpreted as false:
1666``False``, ``None``, numeric zero of all types, and empty strings and containers
1667(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001668other values are interpreted as true. User-defined objects can customize their
1669truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001670
1671.. index:: operator: not
1672
1673The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1674otherwise.
1675
Georg Brandl116aa622007-08-15 14:28:22 +00001676.. index:: operator: and
1677
1678The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1679returned; otherwise, *y* is evaluated and the resulting value is returned.
1680
1681.. index:: operator: or
1682
1683The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1684returned; otherwise, *y* is evaluated and the resulting value is returned.
1685
Andre Delfino55f41e42018-12-05 16:45:30 -03001686Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
Georg Brandl116aa622007-08-15 14:28:22 +00001687they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001688argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001689replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001690the desired value. Because :keyword:`not` has to create a new value, it
1691returns a boolean value regardless of the type of its argument
1692(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001693
1694
Brandt Bucher8bae2192020-03-05 21:19:22 -08001695Assignment expressions
1696======================
1697
Victor Stinner8af239e2020-09-18 09:10:15 +02001698.. productionlist:: python-grammar
Brandt Bucher8bae2192020-03-05 21:19:22 -08001699 assignment_expression: [`identifier` ":="] `expression`
1700
Shankar Jhaf117cef2020-07-26 05:03:48 +05301701An assignment expression (sometimes also called a "named expression" or
1702"walrus") assigns an :token:`expression` to an :token:`identifier`, while also
1703returning the value of the :token:`expression`.
Brandt Bucher8bae2192020-03-05 21:19:22 -08001704
Shankar Jhaf117cef2020-07-26 05:03:48 +05301705One common use case is when handling matched regular expressions:
1706
1707.. code-block:: python
1708
1709 if matching := pattern.search(data):
1710 do_something(matching)
1711
1712Or, when processing a file stream in chunks:
1713
1714.. code-block:: python
1715
1716 while chunk := file.read(9000):
1717 process(chunk)
1718
1719.. versionadded:: 3.8
1720 See :pep:`572` for more details about assignment expressions.
Brandt Bucher8bae2192020-03-05 21:19:22 -08001721
1722
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001723.. _if_expr:
1724
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001725Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001726=======================
1727
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001728.. index::
1729 pair: conditional; expression
1730 pair: ternary; operator
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001731 single: if; conditional expression
1732 single: else; conditional expression
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001733
Victor Stinner8af239e2020-09-18 09:10:15 +02001734.. productionlist:: python-grammar
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001735 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001736 expression: `conditional_expression` | `lambda_expr`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001737
1738Conditional expressions (sometimes called a "ternary operator") have the lowest
1739priority of all Python operations.
1740
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001741The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1742If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001743evaluated and its value is returned.
1744
1745See :pep:`308` for more details about conditional expressions.
1746
1747
Georg Brandl116aa622007-08-15 14:28:22 +00001748.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001749.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001750
1751Lambdas
1752=======
1753
1754.. index::
1755 pair: lambda; expression
1756 pair: lambda; form
1757 pair: anonymous; function
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001758 single: : (colon); lambda expression
Georg Brandl116aa622007-08-15 14:28:22 +00001759
Victor Stinner8af239e2020-09-18 09:10:15 +02001760.. productionlist:: python-grammar
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001761 lambda_expr: "lambda" [`parameter_list`] ":" `expression`
Georg Brandl116aa622007-08-15 14:28:22 +00001762
Zachary Ware2f78b842014-06-03 09:32:40 -05001763Lambda expressions (sometimes called lambda forms) are used to create anonymous
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001764functions. The expression ``lambda parameters: expression`` yields a function
Martin Panter1050d2d2016-07-26 11:18:21 +02001765object. The unnamed object behaves like a function object defined with:
1766
1767.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +00001768
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001769 def <lambda>(parameters):
Georg Brandl116aa622007-08-15 14:28:22 +00001770 return expression
1771
1772See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001773functions created with lambda expressions cannot contain statements or
1774annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001775
Georg Brandl116aa622007-08-15 14:28:22 +00001776
1777.. _exprlists:
1778
1779Expression lists
1780================
1781
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001782.. index::
1783 pair: expression; list
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001784 single: , (comma); expression list
Georg Brandl116aa622007-08-15 14:28:22 +00001785
Victor Stinner8af239e2020-09-18 09:10:15 +02001786.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -03001787 expression_list: `expression` ("," `expression`)* [","]
1788 starred_list: `starred_item` ("," `starred_item`)* [","]
1789 starred_expression: `expression` | (`starred_item` ",")* [`starred_item`]
Brandt Bucher8bae2192020-03-05 21:19:22 -08001790 starred_item: `assignment_expression` | "*" `or_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001791
1792.. index:: object: tuple
1793
Martin Panter0c0da482016-06-12 01:46:50 +00001794Except when part of a list or set display, an expression list
1795containing at least one comma yields a tuple. The length of
Georg Brandl116aa622007-08-15 14:28:22 +00001796the tuple is the number of expressions in the list. The expressions are
1797evaluated from left to right.
1798
Martin Panter0c0da482016-06-12 01:46:50 +00001799.. index::
1800 pair: iterable; unpacking
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001801 single: * (asterisk); in expression lists
Martin Panter0c0da482016-06-12 01:46:50 +00001802
1803An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be
1804an :term:`iterable`. The iterable is expanded into a sequence of items,
1805which are included in the new tuple, list, or set, at the site of
1806the unpacking.
1807
1808.. versionadded:: 3.5
1809 Iterable unpacking in expression lists, originally proposed by :pep:`448`.
1810
Georg Brandl116aa622007-08-15 14:28:22 +00001811.. index:: pair: trailing; comma
1812
1813The trailing comma is required only to create a single tuple (a.k.a. a
1814*singleton*); it is optional in all other cases. A single expression without a
1815trailing comma doesn't create a tuple, but rather yields the value of that
1816expression. (To create an empty tuple, use an empty pair of parentheses:
1817``()``.)
1818
1819
1820.. _evalorder:
1821
1822Evaluation order
1823================
1824
1825.. index:: pair: evaluation; order
1826
Georg Brandl96593ed2007-09-07 14:15:41 +00001827Python evaluates expressions from left to right. Notice that while evaluating
1828an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001829
1830In the following lines, expressions will be evaluated in the arithmetic order of
1831their suffixes::
1832
1833 expr1, expr2, expr3, expr4
1834 (expr1, expr2, expr3, expr4)
1835 {expr1: expr2, expr3: expr4}
1836 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001837 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001838 expr3, expr4 = expr1, expr2
1839
1840
1841.. _operator-summary:
1842
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001843Operator precedence
1844===================
Georg Brandl116aa622007-08-15 14:28:22 +00001845
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001846.. index::
1847 pair: operator; precedence
Georg Brandl116aa622007-08-15 14:28:22 +00001848
Ammar Askar68ba0c62021-04-19 11:22:03 -04001849The following table summarizes the operator precedence in Python, from highest
1850precedence (most binding) to lowest precedence (least binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001851the same box have the same precedence. Unless the syntax is explicitly given,
1852operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001853exponentiation, which groups from right to left).
1854
1855Note that comparisons, membership tests, and identity tests, all have the same
1856precedence and have a left-to-right chaining feature as described in the
1857:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001858
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001859
1860+-----------------------------------------------+-------------------------------------+
1861| Operator | Description |
1862+===============================================+=====================================+
Andre Delfinodc269972019-09-11 10:16:11 -03001863| ``(expressions...)``, | Binding or parenthesized |
1864| | expression, |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001865| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001866| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001867| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001868+-----------------------------------------------+-------------------------------------+
Ammar Askar68ba0c62021-04-19 11:22:03 -04001869| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1870| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1871+-----------------------------------------------+-------------------------------------+
1872| :keyword:`await` ``x`` | Await expression |
1873+-----------------------------------------------+-------------------------------------+
1874| ``**`` | Exponentiation [#]_ |
1875+-----------------------------------------------+-------------------------------------+
1876| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1877+-----------------------------------------------+-------------------------------------+
1878| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
1879| | multiplication, division, floor |
1880| | division, remainder [#]_ |
1881+-----------------------------------------------+-------------------------------------+
1882| ``+``, ``-`` | Addition and subtraction |
1883+-----------------------------------------------+-------------------------------------+
1884| ``<<``, ``>>`` | Shifts |
1885+-----------------------------------------------+-------------------------------------+
1886| ``&`` | Bitwise AND |
1887+-----------------------------------------------+-------------------------------------+
1888| ``^`` | Bitwise XOR |
1889+-----------------------------------------------+-------------------------------------+
1890| ``|`` | Bitwise OR |
1891+-----------------------------------------------+-------------------------------------+
1892| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
1893| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
1894| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
1895+-----------------------------------------------+-------------------------------------+
1896| :keyword:`not` ``x`` | Boolean NOT |
1897+-----------------------------------------------+-------------------------------------+
1898| :keyword:`and` | Boolean AND |
1899+-----------------------------------------------+-------------------------------------+
1900| :keyword:`or` | Boolean OR |
1901+-----------------------------------------------+-------------------------------------+
1902| :keyword:`if <if_expr>` -- :keyword:`!else` | Conditional expression |
1903+-----------------------------------------------+-------------------------------------+
1904| :keyword:`lambda` | Lambda expression |
1905+-----------------------------------------------+-------------------------------------+
1906| ``:=`` | Assignment expression |
1907+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001908
Georg Brandl116aa622007-08-15 14:28:22 +00001909
1910.. rubric:: Footnotes
1911
Georg Brandl116aa622007-08-15 14:28:22 +00001912.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1913 true numerically due to roundoff. For example, and assuming a platform on which
1914 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1915 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001916 1e100``, which is numerically exactly equal to ``1e100``. The function
1917 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001918 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1919 is more appropriate depends on the application.
1920
1921.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001922 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001923 cases, Python returns the latter result, in order to preserve that
1924 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1925
Martin Panteraa0da862015-09-23 05:28:13 +00001926.. [#] The Unicode standard distinguishes between :dfn:`code points`
1927 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
1928 While most abstract characters in Unicode are only represented using one
1929 code point, there is a number of abstract characters that can in addition be
1930 represented using a sequence of more than one code point. For example, the
1931 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
1932 as a single :dfn:`precomposed character` at code position U+00C7, or as a
1933 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
1934 LETTER C), followed by a :dfn:`combining character` at code position U+0327
1935 (COMBINING CEDILLA).
1936
1937 The comparison operators on strings compare at the level of Unicode code
1938 points. This may be counter-intuitive to humans. For example,
1939 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1940 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".
1941
1942 To compare strings at the level of abstract characters (that is, in a way
1943 intuitive to humans), use :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001944
Georg Brandl48310cd2009-01-03 21:18:54 +00001945.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001946 descriptors, you may notice seemingly unusual behaviour in certain uses of
1947 the :keyword:`is` operator, like those involving comparisons between instance
1948 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001949
1950.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1951 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.
Zackery Spytz7d2b83e2021-05-02 10:29:15 -07001952
1953.. [#] The ``%`` operator is also used for string formatting; the same
1954 precedence applies.