blob: 17f1f2c7b318b49db22b5733505d7bee86ea2289 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2.. _expressions:
3
4***********
5Expressions
6***********
7
Georg Brandl4b491312007-08-31 09:22:56 +00008.. index:: expression, BNF
Georg Brandl116aa622007-08-15 14:28:22 +00009
Brett Cannon7603fa02011-01-06 23:08:16 +000010This chapter explains the meaning of the elements of expressions in Python.
Georg Brandl116aa622007-08-15 14:28:22 +000011
Georg Brandl116aa622007-08-15 14:28:22 +000012**Syntax Notes:** In this and the following chapters, extended BNF notation will
13be used to describe syntax, not lexical analysis. When (one alternative of) a
14syntax rule has the form
15
16.. productionlist:: *
17 name: `othername`
18
Georg Brandl116aa622007-08-15 14:28:22 +000019and no semantics are given, the semantics of this form of ``name`` are the same
20as for ``othername``.
21
22
23.. _conversions:
24
25Arithmetic conversions
26======================
27
28.. index:: pair: arithmetic; conversion
29
Georg Brandl116aa622007-08-15 14:28:22 +000030When a description of an arithmetic operator below uses the phrase "the numeric
Georg Brandl96593ed2007-09-07 14:15:41 +000031arguments are converted to a common type," this means that the operator
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070032implementation for built-in types works as follows:
Georg Brandl116aa622007-08-15 14:28:22 +000033
34* If either argument is a complex number, the other is converted to complex;
35
36* otherwise, if either argument is a floating point number, the other is
37 converted to floating point;
38
Georg Brandl96593ed2007-09-07 14:15:41 +000039* otherwise, both must be integers and no conversion is necessary.
Georg Brandl116aa622007-08-15 14:28:22 +000040
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070041Some additional rules apply for certain operators (e.g., a string as a left
42argument to the '%' operator). Extensions must define their own conversion
43behavior.
Georg Brandl116aa622007-08-15 14:28:22 +000044
45
46.. _atoms:
47
48Atoms
49=====
50
Georg Brandl96593ed2007-09-07 14:15:41 +000051.. index:: atom
Georg Brandl116aa622007-08-15 14:28:22 +000052
53Atoms are the most basic elements of expressions. The simplest atoms are
Georg Brandl96593ed2007-09-07 14:15:41 +000054identifiers or literals. Forms enclosed in parentheses, brackets or braces are
55also categorized syntactically as atoms. The syntax for atoms is:
Georg Brandl116aa622007-08-15 14:28:22 +000056
57.. productionlist::
58 atom: `identifier` | `literal` | `enclosure`
Georg Brandl96593ed2007-09-07 14:15:41 +000059 enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display`
60 : | `generator_expression` | `yield_atom`
Georg Brandl116aa622007-08-15 14:28:22 +000061
62
63.. _atom-identifiers:
64
65Identifiers (Names)
66-------------------
67
Georg Brandl96593ed2007-09-07 14:15:41 +000068.. index:: name, identifier
Georg Brandl116aa622007-08-15 14:28:22 +000069
70An identifier occurring as an atom is a name. See section :ref:`identifiers`
71for lexical definition and section :ref:`naming` for documentation of naming and
72binding.
73
74.. index:: exception: NameError
75
76When the name is bound to an object, evaluation of the atom yields that object.
77When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
78exception.
79
80.. index::
81 pair: name; mangling
82 pair: private; names
83
84**Private name mangling:** When an identifier that textually occurs in a class
85definition begins with two or more underscore characters and does not end in two
86or more underscores, it is considered a :dfn:`private name` of that class.
87Private names are transformed to a longer form before code is generated for
Georg Brandldec3b3f2013-04-14 10:13:42 +020088them. The transformation inserts the class name, with leading underscores
89removed and a single underscore inserted, in front of the name. For example,
90the identifier ``__spam`` occurring in a class named ``Ham`` will be transformed
91to ``_Ham__spam``. This transformation is independent of the syntactical
92context in which the identifier is used. If the transformed name is extremely
93long (longer than 255 characters), implementation defined truncation may happen.
94If the class name consists only of underscores, no transformation is done.
Georg Brandl116aa622007-08-15 14:28:22 +000095
Georg Brandl116aa622007-08-15 14:28:22 +000096
97.. _atom-literals:
98
99Literals
100--------
101
102.. index:: single: literal
103
Georg Brandl96593ed2007-09-07 14:15:41 +0000104Python supports string and bytes literals and various numeric literals:
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000107 literal: `stringliteral` | `bytesliteral`
108 : | `integer` | `floatnumber` | `imagnumber`
Georg Brandl116aa622007-08-15 14:28:22 +0000109
Georg Brandl96593ed2007-09-07 14:15:41 +0000110Evaluation of a literal yields an object of the given type (string, bytes,
111integer, floating point number, complex number) with the given value. The value
112may be approximated in the case of floating point and imaginary (complex)
Georg Brandl116aa622007-08-15 14:28:22 +0000113literals. See section :ref:`literals` for details.
114
115.. index::
116 triple: immutable; data; type
117 pair: immutable; object
118
Terry Jan Reedyead1de22012-02-17 19:56:58 -0500119All literals correspond to immutable data types, and hence the object's identity
120is less important than its value. Multiple evaluations of literals with the
121same value (either the same occurrence in the program text or a different
122occurrence) may obtain the same object or a different object with the same
123value.
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125
126.. _parenthesized:
127
128Parenthesized forms
129-------------------
130
131.. index:: single: parenthesized form
132
133A parenthesized form is an optional expression list enclosed in parentheses:
134
135.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000136 parenth_form: "(" [`starred_expression`] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138A parenthesized expression list yields whatever that expression list yields: if
139the list contains at least one comma, it yields a tuple; otherwise, it yields
140the single expression that makes up the expression list.
141
142.. index:: pair: empty; tuple
143
144An empty pair of parentheses yields an empty tuple object. Since tuples are
145immutable, the rules for literals apply (i.e., two occurrences of the empty
146tuple may or may not yield the same object).
147
148.. index::
149 single: comma
150 pair: tuple; display
151
152Note that tuples are not formed by the parentheses, but rather by use of the
153comma operator. The exception is the empty tuple, for which parentheses *are*
154required --- allowing unparenthesized "nothing" in expressions would cause
155ambiguities and allow common typos to pass uncaught.
156
157
Georg Brandl96593ed2007-09-07 14:15:41 +0000158.. _comprehensions:
159
160Displays for lists, sets and dictionaries
161-----------------------------------------
162
163For constructing a list, a set or a dictionary Python provides special syntax
164called "displays", each of them in two flavors:
165
166* either the container contents are listed explicitly, or
167
168* they are computed via a set of looping and filtering instructions, called a
169 :dfn:`comprehension`.
170
171Common syntax elements for comprehensions are:
172
173.. productionlist::
174 comprehension: `expression` `comp_for`
Serhiy Storchakad08972f2018-04-11 19:15:51 +0300175 comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`]
Georg Brandl96593ed2007-09-07 14:15:41 +0000176 comp_iter: `comp_for` | `comp_if`
177 comp_if: "if" `expression_nocond` [`comp_iter`]
178
179The comprehension consists of a single expression followed by at least one
180:keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` clauses.
181In this case, the elements of the new container are those that would be produced
182by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
183nesting from left to right, and evaluating the expression to produce an element
184each time the innermost block is reached.
185
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200186However, aside from the iterable expression in the leftmost :keyword:`for` clause,
187the comprehension is executed in a separate implicitly nested scope. This ensures
188that names assigned to in the target list don't "leak" into the enclosing scope.
189
190The iterable expression in the leftmost :keyword:`for` clause is evaluated
191directly in the enclosing scope and then passed as an argument to the implictly
192nested scope. Subsequent :keyword:`for` clauses and any filter condition in the
193leftmost :keyword:`for` clause cannot be evaluated in the enclosing scope as
194they may depend on the values obtained from the leftmost iterable. For example:
195``[x*y for x in range(10) for y in range(x, x+10)]``.
196
197To ensure the comprehension always results in a container of the appropriate
198type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200199nested scope.
Georg Brandl02c30562007-09-07 17:52:53 +0000200
Yury Selivanov03660042016-12-15 17:36:05 -0500201Since Python 3.6, in an :keyword:`async def` function, an :keyword:`async for`
202clause may be used to iterate over a :term:`asynchronous iterator`.
203A comprehension in an :keyword:`async def` function may consist of either a
204:keyword:`for` or :keyword:`async for` clause following the leading
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +0200205expression, may contain additional :keyword:`for` or :keyword:`async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500206clauses, and may also use :keyword:`await` expressions.
207If a comprehension contains either :keyword:`async for` clauses
208or :keyword:`await` expressions it is called an
209:dfn:`asynchronous comprehension`. An asynchronous comprehension may
210suspend the execution of the coroutine function in which it appears.
211See also :pep:`530`.
Georg Brandl96593ed2007-09-07 14:15:41 +0000212
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200213.. versionadded:: 3.6
214 Asynchronous comprehensions were introduced.
215
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200216.. versionchanged:: 3.8
217 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200218
219
Georg Brandl116aa622007-08-15 14:28:22 +0000220.. _lists:
221
222List displays
223-------------
224
225.. index::
226 pair: list; display
227 pair: list; comprehensions
Georg Brandl96593ed2007-09-07 14:15:41 +0000228 pair: empty; list
229 object: list
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231A list display is a possibly empty series of expressions enclosed in square
232brackets:
233
234.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000235 list_display: "[" [`starred_list` | `comprehension`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Georg Brandl96593ed2007-09-07 14:15:41 +0000237A list display yields a new list object, the contents being specified by either
238a list of expressions or a comprehension. When a comma-separated list of
239expressions is supplied, its elements are evaluated from left to right and
240placed into the list object in that order. When a comprehension is supplied,
241the list is constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243
Georg Brandl96593ed2007-09-07 14:15:41 +0000244.. _set:
Georg Brandl116aa622007-08-15 14:28:22 +0000245
Georg Brandl96593ed2007-09-07 14:15:41 +0000246Set displays
247------------
Georg Brandl116aa622007-08-15 14:28:22 +0000248
Georg Brandl96593ed2007-09-07 14:15:41 +0000249.. index:: pair: set; display
250 object: set
Georg Brandl116aa622007-08-15 14:28:22 +0000251
Georg Brandl96593ed2007-09-07 14:15:41 +0000252A set display is denoted by curly braces and distinguishable from dictionary
253displays by the lack of colons separating keys and values:
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000256 set_display: "{" (`starred_list` | `comprehension`) "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000257
Georg Brandl96593ed2007-09-07 14:15:41 +0000258A set display yields a new mutable set object, the contents being specified by
259either a sequence of expressions or a comprehension. When a comma-separated
260list of expressions is supplied, its elements are evaluated from left to right
261and added to the set object. When a comprehension is supplied, the set is
262constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000263
Georg Brandl528cdb12008-09-21 07:09:51 +0000264An empty set cannot be constructed with ``{}``; this literal constructs an empty
265dictionary.
Christian Heimes78644762008-03-04 23:39:23 +0000266
267
Georg Brandl116aa622007-08-15 14:28:22 +0000268.. _dict:
269
270Dictionary displays
271-------------------
272
273.. index:: pair: dictionary; display
Georg Brandl96593ed2007-09-07 14:15:41 +0000274 key, datum, key/datum pair
275 object: dictionary
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277A dictionary display is a possibly empty series of key/datum pairs enclosed in
278curly braces:
279
280.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000281 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000282 key_datum_list: `key_datum` ("," `key_datum`)* [","]
Martin Panter0c0da482016-06-12 01:46:50 +0000283 key_datum: `expression` ":" `expression` | "**" `or_expr`
Georg Brandl96593ed2007-09-07 14:15:41 +0000284 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286A dictionary display yields a new dictionary object.
287
Georg Brandl96593ed2007-09-07 14:15:41 +0000288If a comma-separated sequence of key/datum pairs is given, they are evaluated
289from left to right to define the entries of the dictionary: each key object is
290used as a key into the dictionary to store the corresponding datum. This means
291that you can specify the same key multiple times in the key/datum list, and the
292final dictionary's value for that key will be the last one given.
293
Martin Panter0c0da482016-06-12 01:46:50 +0000294.. index:: unpacking; dictionary, **; in dictionary displays
295
296A double asterisk ``**`` denotes :dfn:`dictionary unpacking`.
297Its operand must be a :term:`mapping`. Each mapping item is added
298to the new dictionary. Later values replace values already set by
299earlier key/datum pairs and earlier dictionary unpackings.
300
301.. versionadded:: 3.5
302 Unpacking into dictionary displays, originally proposed by :pep:`448`.
303
Georg Brandl96593ed2007-09-07 14:15:41 +0000304A dict comprehension, in contrast to list and set comprehensions, needs two
305expressions separated with a colon followed by the usual "for" and "if" clauses.
306When the comprehension is run, the resulting key and value elements are inserted
307in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000310 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000313:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000314all mutable objects.) Clashes between duplicate keys are not detected; the last
315datum (textually rightmost in the display) stored for a given key value
316prevails.
317
318
Georg Brandl96593ed2007-09-07 14:15:41 +0000319.. _genexpr:
320
321Generator expressions
322---------------------
323
324.. index:: pair: generator; expression
325 object: generator
326
327A generator expression is a compact generator notation in parentheses:
328
329.. productionlist::
330 generator_expression: "(" `expression` `comp_for` ")"
331
332A generator expression yields a new generator object. Its syntax is the same as
333for comprehensions, except that it is enclosed in parentheses instead of
334brackets or curly braces.
335
336Variables used in the generator expression are evaluated lazily when the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700337:meth:`~generator.__next__` method is called for the generator object (in the same
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200338fashion as normal generators). However, the iterable expression in the
339leftmost :keyword:`for` clause is immediately evaluated, so that an error
340produced by it will be emitted at the point where the generator expression
341is defined, rather than at the point where the first value is retrieved.
342Subsequent :keyword:`for` clauses and any filter condition in the leftmost
343:keyword:`for` clause cannot be evaluated in the enclosing scope as they may
344depend on the values obtained from the leftmost iterable. For example:
345``(x*y for x in range(10) for y in range(x, x+10))``.
Georg Brandl96593ed2007-09-07 14:15:41 +0000346
347The parentheses can be omitted on calls with only one argument. See section
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700348:ref:`calls` for details.
Georg Brandl96593ed2007-09-07 14:15:41 +0000349
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200350To avoid interfering with the expected operation of the generator expression
351itself, ``yield`` and ``yield from`` expressions are prohibited in the
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200352implicitly defined generator.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200353
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400354If a generator expression contains either :keyword:`async for`
355clauses or :keyword:`await` expressions it is called an
356:dfn:`asynchronous generator expression`. An asynchronous generator
357expression returns a new asynchronous generator object,
358which is an asynchronous iterator (see :ref:`async-iterators`).
359
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200360.. versionadded:: 3.6
361 Asynchronous generator expressions were introduced.
362
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400363.. versionchanged:: 3.7
364 Prior to Python 3.7, asynchronous generator expressions could
365 only appear in :keyword:`async def` coroutines. Starting
366 with 3.7, any function can use asynchronous generator expressions.
Georg Brandl96593ed2007-09-07 14:15:41 +0000367
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200368.. versionchanged:: 3.8
369 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200370
371
Georg Brandl116aa622007-08-15 14:28:22 +0000372.. _yieldexpr:
373
374Yield expressions
375-----------------
376
377.. index::
378 keyword: yield
379 pair: yield; expression
380 pair: generator; function
381
382.. productionlist::
383 yield_atom: "(" `yield_expression` ")"
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000384 yield_expression: "yield" [`expression_list` | "from" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000385
Yury Selivanov03660042016-12-15 17:36:05 -0500386The yield expression is used when defining a :term:`generator` function
387or an :term:`asynchronous generator` function and
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500388thus can only be used in the body of a function definition. Using a yield
Yury Selivanov03660042016-12-15 17:36:05 -0500389expression in a function's body causes that function to be a generator,
390and using it in an :keyword:`async def` function's body causes that
391coroutine function to be an asynchronous generator. For example::
392
393 def gen(): # defines a generator function
394 yield 123
395
396 async def agen(): # defines an asynchronous generator function (PEP 525)
397 yield 123
398
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200399Due to their side effects on the containing scope, ``yield`` expressions
400are not permitted as part of the implicitly defined scopes used to
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200401implement comprehensions and generator expressions.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200402
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200403.. versionchanged:: 3.8
404 Yield expressions prohibited in the implicitly nested scopes used to
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200405 implement comprehensions and generator expressions.
406
Yury Selivanov03660042016-12-15 17:36:05 -0500407Generator functions are described below, while asynchronous generator
408functions are described separately in section
409:ref:`asynchronous-generator-functions`.
Georg Brandl116aa622007-08-15 14:28:22 +0000410
411When a generator function is called, it returns an iterator known as a
Guido van Rossumd0150ad2015-05-05 12:02:01 -0700412generator. That generator then controls the execution of the generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000413The execution starts when one of the generator's methods is called. At that
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500414time, the execution proceeds to the first yield expression, where it is
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700415suspended again, returning the value of :token:`expression_list` to the generator's
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500416caller. By suspended, we mean that all local state is retained, including the
Ethan Furman2f825af2015-01-14 22:25:27 -0800417current bindings of local variables, the instruction pointer, the internal
418evaluation stack, and the state of any exception handling. When the execution
419is resumed by calling one of the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500420generator's methods, the function can proceed exactly as if the yield expression
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700421were just another external call. The value of the yield expression after
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500422resuming depends on the method which resumed the execution. If
423:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or
424the :func:`next` builtin) then the result is :const:`None`. Otherwise, if
425:meth:`~generator.send` is used, then the result will be the value passed in to
426that method.
Georg Brandl116aa622007-08-15 14:28:22 +0000427
428.. index:: single: coroutine
429
430All of this makes generator functions quite similar to coroutines; they yield
431multiple times, they have more than one entry point and their execution can be
432suspended. The only difference is that a generator function cannot control
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700433where the execution should continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000434transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000435
Ethan Furman2f825af2015-01-14 22:25:27 -0800436Yield expressions are allowed anywhere in a :keyword:`try` construct. If the
437generator is not resumed before it is
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500438finalized (by reaching a zero reference count or by being garbage collected),
439the generator-iterator's :meth:`~generator.close` method will be called,
440allowing any pending :keyword:`finally` clauses to execute.
Georg Brandl02c30562007-09-07 17:52:53 +0000441
Nick Coghlan0ed80192012-01-14 14:43:24 +1000442When ``yield from <expr>`` is used, it treats the supplied expression as
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000443a subiterator. All values produced by that subiterator are passed directly
444to the caller of the current generator's methods. Any values passed in with
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300445:meth:`~generator.send` and any exceptions passed in with
446:meth:`~generator.throw` are passed to the underlying iterator if it has the
447appropriate methods. If this is not the case, then :meth:`~generator.send`
448will raise :exc:`AttributeError` or :exc:`TypeError`, while
449:meth:`~generator.throw` will just raise the passed in exception immediately.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000450
451When the underlying iterator is complete, the :attr:`~StopIteration.value`
452attribute of the raised :exc:`StopIteration` instance becomes the value of
453the yield expression. It can be either set explicitly when raising
454:exc:`StopIteration`, or automatically when the sub-iterator is a generator
455(by returning a value from the sub-generator).
456
Nick Coghlan0ed80192012-01-14 14:43:24 +1000457 .. versionchanged:: 3.3
Martin Panterd21e0b52015-10-10 10:36:22 +0000458 Added ``yield from <expr>`` to delegate control flow to a subiterator.
Nick Coghlan0ed80192012-01-14 14:43:24 +1000459
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500460The parentheses may be omitted when the yield expression is the sole expression
461on the right hand side of an assignment statement.
462
463.. seealso::
464
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300465 :pep:`255` - Simple Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500466 The proposal for adding generators and the :keyword:`yield` statement to Python.
467
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300468 :pep:`342` - Coroutines via Enhanced Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500469 The proposal to enhance the API and syntax of generators, making them
470 usable as simple coroutines.
471
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300472 :pep:`380` - Syntax for Delegating to a Subgenerator
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500473 The proposal to introduce the :token:`yield_from` syntax, making delegation
474 to sub-generators easy.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000475
Georg Brandl116aa622007-08-15 14:28:22 +0000476.. index:: object: generator
Yury Selivanov66f88282015-06-24 11:04:15 -0400477.. _generator-methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000478
R David Murray2c1d1d62012-08-17 20:48:59 -0400479Generator-iterator methods
480^^^^^^^^^^^^^^^^^^^^^^^^^^
481
482This subsection describes the methods of a generator iterator. They can
483be used to control the execution of a generator function.
484
485Note that calling any of the generator methods below when the generator
486is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000487
488.. index:: exception: StopIteration
489
490
Georg Brandl96593ed2007-09-07 14:15:41 +0000491.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000492
Georg Brandl96593ed2007-09-07 14:15:41 +0000493 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500494 executed yield expression. When a generator function is resumed with a
495 :meth:`~generator.__next__` method, the current yield expression always
496 evaluates to :const:`None`. The execution then continues to the next yield
497 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300498 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500499 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000500 exception is raised.
501
502 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
503 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000504
505
506.. method:: generator.send(value)
507
508 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500509 *value* argument becomes the result of the current yield expression. The
510 :meth:`send` method returns the next value yielded by the generator, or
511 raises :exc:`StopIteration` if the generator exits without yielding another
512 value. When :meth:`send` is called to start the generator, it must be called
513 with :const:`None` as the argument, because there is no yield expression that
514 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516
517.. method:: generator.throw(type[, value[, traceback]])
518
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700519 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000520 and returns the next value yielded by the generator function. If the generator
521 exits without yielding another value, a :exc:`StopIteration` exception is
522 raised. If the generator function does not catch the passed-in exception, or
523 raises a different exception, then that exception propagates to the caller.
524
525.. index:: exception: GeneratorExit
526
527
528.. method:: generator.close()
529
530 Raises a :exc:`GeneratorExit` at the point where the generator function was
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400531 paused. If the generator function then exits gracefully, is already closed,
532 or raises :exc:`GeneratorExit` (by not catching the exception), close
533 returns to its caller. If the generator yields a value, a
534 :exc:`RuntimeError` is raised. If the generator raises any other exception,
535 it is propagated to the caller. :meth:`close` does nothing if the generator
536 has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000537
Chris Jerdonek2654b862012-12-23 15:31:57 -0800538.. index:: single: yield; examples
539
540Examples
541^^^^^^^^
542
Georg Brandl116aa622007-08-15 14:28:22 +0000543Here is a simple example that demonstrates the behavior of generators and
544generator functions::
545
546 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000547 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000548 ... try:
549 ... while True:
550 ... try:
551 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000552 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000553 ... value = e
554 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000555 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000556 ...
557 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000558 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000559 Execution starts when 'next()' is called for the first time.
560 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000561 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000562 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000563 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000564 2
565 >>> generator.throw(TypeError, "spam")
566 TypeError('spam',)
567 >>> generator.close()
568 Don't forget to clean up when 'close()' is called.
569
Chris Jerdonek2654b862012-12-23 15:31:57 -0800570For examples using ``yield from``, see :ref:`pep-380` in "What's New in
571Python."
572
Yury Selivanov03660042016-12-15 17:36:05 -0500573.. _asynchronous-generator-functions:
574
575Asynchronous generator functions
576^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
577
578The presence of a yield expression in a function or method defined using
579:keyword:`async def` further defines the function as a
580:term:`asynchronous generator` function.
581
582When an asynchronous generator function is called, it returns an
583asynchronous iterator known as an asynchronous generator object.
584That object then controls the execution of the generator function.
585An asynchronous generator object is typically used in an
586:keyword:`async for` statement in a coroutine function analogously to
587how a generator object would be used in a :keyword:`for` statement.
588
589Calling one of the asynchronous generator's methods returns an
590:term:`awaitable` object, and the execution starts when this object
591is awaited on. At that time, the execution proceeds to the first yield
592expression, where it is suspended again, returning the value of
593:token:`expression_list` to the awaiting coroutine. As with a generator,
594suspension means that all local state is retained, including the
595current bindings of local variables, the instruction pointer, the internal
596evaluation stack, and the state of any exception handling. When the execution
597is resumed by awaiting on the next object returned by the asynchronous
598generator's methods, the function can proceed exactly as if the yield
599expression were just another external call. The value of the yield expression
600after resuming depends on the method which resumed the execution. If
601:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
602:meth:`~agen.asend` is used, then the result will be the value passed in to
603that method.
604
605In an asynchronous generator function, yield expressions are allowed anywhere
606in a :keyword:`try` construct. However, if an asynchronous generator is not
607resumed before it is finalized (by reaching a zero reference count or by
608being garbage collected), then a yield expression within a :keyword:`try`
609construct could result in a failure to execute pending :keyword:`finally`
610clauses. In this case, it is the responsibility of the event loop or
611scheduler running the asynchronous generator to call the asynchronous
612generator-iterator's :meth:`~agen.aclose` method and run the resulting
613coroutine object, thus allowing any pending :keyword:`finally` clauses
614to execute.
615
616To take care of finalization, an event loop should define
617a *finalizer* function which takes an asynchronous generator-iterator
618and presumably calls :meth:`~agen.aclose` and executes the coroutine.
619This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`.
620When first iterated over, an asynchronous generator-iterator will store the
621registered *finalizer* to be called upon finalization. For a reference example
622of a *finalizer* method see the implementation of
623``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`.
624
625The expression ``yield from <expr>`` is a syntax error when used in an
626asynchronous generator function.
627
628.. index:: object: asynchronous-generator
629.. _asynchronous-generator-methods:
630
631Asynchronous generator-iterator methods
632^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
633
634This subsection describes the methods of an asynchronous generator iterator,
635which are used to control the execution of a generator function.
636
637
638.. index:: exception: StopAsyncIteration
639
640.. coroutinemethod:: agen.__anext__()
641
642 Returns an awaitable which when run starts to execute the asynchronous
643 generator or resumes it at the last executed yield expression. When an
644 asynchronous generator function is resumed with a :meth:`~agen.__anext__`
645 method, the current yield expression always evaluates to :const:`None` in
646 the returned awaitable, which when run will continue to the next yield
647 expression. The value of the :token:`expression_list` of the yield
648 expression is the value of the :exc:`StopIteration` exception raised by
649 the completing coroutine. If the asynchronous generator exits without
650 yielding another value, the awaitable instead raises an
651 :exc:`StopAsyncIteration` exception, signalling that the asynchronous
652 iteration has completed.
653
654 This method is normally called implicitly by a :keyword:`async for` loop.
655
656
657.. coroutinemethod:: agen.asend(value)
658
659 Returns an awaitable which when run resumes the execution of the
660 asynchronous generator. As with the :meth:`~generator.send()` method for a
661 generator, this "sends" a value into the asynchronous generator function,
662 and the *value* argument becomes the result of the current yield expression.
663 The awaitable returned by the :meth:`asend` method will return the next
664 value yielded by the generator as the value of the raised
665 :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the
666 asynchronous generator exits without yielding another value. When
667 :meth:`asend` is called to start the asynchronous
668 generator, it must be called with :const:`None` as the argument,
669 because there is no yield expression that could receive the value.
670
671
672.. coroutinemethod:: agen.athrow(type[, value[, traceback]])
673
674 Returns an awaitable that raises an exception of type ``type`` at the point
675 where the asynchronous generator was paused, and returns the next value
676 yielded by the generator function as the value of the raised
677 :exc:`StopIteration` exception. If the asynchronous generator exits
678 without yielding another value, an :exc:`StopAsyncIteration` exception is
679 raised by the awaitable.
680 If the generator function does not catch the passed-in exception, or
delirious-lettuce3378b202017-05-19 14:37:57 -0600681 raises a different exception, then when the awaitable is run that exception
Yury Selivanov03660042016-12-15 17:36:05 -0500682 propagates to the caller of the awaitable.
683
684.. index:: exception: GeneratorExit
685
686
687.. coroutinemethod:: agen.aclose()
688
689 Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
690 the asynchronous generator function at the point where it was paused.
691 If the asynchronous generator function then exits gracefully, is already
692 closed, or raises :exc:`GeneratorExit` (by not catching the exception),
693 then the returned awaitable will raise a :exc:`StopIteration` exception.
694 Any further awaitables returned by subsequent calls to the asynchronous
695 generator will raise a :exc:`StopAsyncIteration` exception. If the
696 asynchronous generator yields a value, a :exc:`RuntimeError` is raised
697 by the awaitable. If the asynchronous generator raises any other exception,
698 it is propagated to the caller of the awaitable. If the asynchronous
699 generator has already exited due to an exception or normal exit, then
700 further calls to :meth:`aclose` will return an awaitable that does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
Georg Brandl116aa622007-08-15 14:28:22 +0000702.. _primaries:
703
704Primaries
705=========
706
707.. index:: single: primary
708
709Primaries represent the most tightly bound operations of the language. Their
710syntax is:
711
712.. productionlist::
713 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
714
715
716.. _attribute-references:
717
718Attribute references
719--------------------
720
721.. index:: pair: attribute; reference
722
723An attribute reference is a primary followed by a period and a name:
724
725.. productionlist::
726 attributeref: `primary` "." `identifier`
727
728.. index::
729 exception: AttributeError
730 object: module
731 object: list
732
733The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000734references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700735attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500736overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700737the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
738the object produced is determined by the object. Multiple evaluations of the
739same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741
742.. _subscriptions:
743
744Subscriptions
745-------------
746
747.. index:: single: subscription
748
749.. index::
750 object: sequence
751 object: mapping
752 object: string
753 object: tuple
754 object: list
755 object: dictionary
756 pair: sequence; item
757
758A subscription selects an item of a sequence (string, tuple or list) or mapping
759(dictionary) object:
760
761.. productionlist::
762 subscription: `primary` "[" `expression_list` "]"
763
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700764The primary must evaluate to an object that supports subscription (lists or
765dictionaries for example). User-defined objects can support subscription by
766defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000767
768For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000769
770If the primary is a mapping, the expression list must evaluate to an object
771whose value is one of the keys of the mapping, and the subscription selects the
772value in the mapping that corresponds to that key. (The expression list is a
773tuple except if it has exactly one item.)
774
Andrés Delfino4fddd4e2018-06-15 15:24:25 -0300775If the primary is a sequence, the expression list must evaluate to an integer
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000776or a slice (as discussed in the following section).
777
778The formal syntax makes no special provision for negative indices in
779sequences; however, built-in sequences all provide a :meth:`__getitem__`
780method that interprets negative indices by adding the length of the sequence
781to the index (so that ``x[-1]`` selects the last item of ``x``). The
782resulting value must be a nonnegative integer less than the number of items in
783the sequence, and the subscription selects the item whose index is that value
784(counting from zero). Since the support for negative indices and slicing
785occurs in the object's :meth:`__getitem__` method, subclasses overriding
786this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000787
788.. index::
789 single: character
790 pair: string; item
791
792A string's items are characters. A character is not a separate data type but a
793string of exactly one character.
794
795
796.. _slicings:
797
798Slicings
799--------
800
801.. index::
802 single: slicing
803 single: slice
804
805.. index::
806 object: sequence
807 object: string
808 object: tuple
809 object: list
810
811A slicing selects a range of items in a sequence object (e.g., a string, tuple
812or list). Slicings may be used as expressions or as targets in assignment or
813:keyword:`del` statements. The syntax for a slicing:
814
815.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000816 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000817 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000818 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000819 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000820 lower_bound: `expression`
821 upper_bound: `expression`
822 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000823
824There is ambiguity in the formal syntax here: anything that looks like an
825expression list also looks like a slice list, so any subscription can be
826interpreted as a slicing. Rather than further complicating the syntax, this is
827disambiguated by defining that in this case the interpretation as a subscription
828takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000829slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000830
831.. index::
832 single: start (slice object attribute)
833 single: stop (slice object attribute)
834 single: step (slice object attribute)
835
Georg Brandla4c8c472014-10-31 10:38:49 +0100836The semantics for a slicing are as follows. The primary is indexed (using the
837same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000838normal subscription) with a key that is constructed from the slice list, as
839follows. If the slice list contains at least one comma, the key is a tuple
840containing the conversion of the slice items; otherwise, the conversion of the
841lone slice item is the key. The conversion of a slice item that is an
842expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300843object (see section :ref:`types`) whose :attr:`~slice.start`,
844:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
845expressions given as lower bound, upper bound and stride, respectively,
846substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000847
848
Chris Jerdonekb4309942012-12-25 14:54:44 -0800849.. index::
850 object: callable
851 single: call
852 single: argument; call semantics
853
Georg Brandl116aa622007-08-15 14:28:22 +0000854.. _calls:
855
856Calls
857-----
858
Chris Jerdonekb4309942012-12-25 14:54:44 -0800859A call calls a callable object (e.g., a :term:`function`) with a possibly empty
860series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000861
862.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000863 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Martin Panter0c0da482016-06-12 01:46:50 +0000864 argument_list: `positional_arguments` ["," `starred_and_keywords`]
865 : ["," `keywords_arguments`]
866 : | `starred_and_keywords` ["," `keywords_arguments`]
867 : | `keywords_arguments`
868 positional_arguments: ["*"] `expression` ("," ["*"] `expression`)*
869 starred_and_keywords: ("*" `expression` | `keyword_item`)
870 : ("," "*" `expression` | "," `keyword_item`)*
871 keywords_arguments: (`keyword_item` | "**" `expression`)
Martin Panter7106a512016-12-24 10:20:38 +0000872 : ("," `keyword_item` | "," "**" `expression`)*
Georg Brandl116aa622007-08-15 14:28:22 +0000873 keyword_item: `identifier` "=" `expression`
874
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700875An optional trailing comma may be present after the positional and keyword arguments
876but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000877
Chris Jerdonekb4309942012-12-25 14:54:44 -0800878.. index::
879 single: parameter; call semantics
880
Georg Brandl116aa622007-08-15 14:28:22 +0000881The primary must evaluate to a callable object (user-defined functions, built-in
882functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000883instances, and all objects having a :meth:`__call__` method are callable). All
884argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800885to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000886
887.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000888
889If keyword arguments are present, they are first converted to positional
890arguments, as follows. First, a list of unfilled slots is created for the
891formal parameters. If there are N positional arguments, they are placed in the
892first N slots. Next, for each keyword argument, the identifier is used to
893determine the corresponding slot (if the identifier is the same as the first
894formal parameter name, the first slot is used, and so on). If the slot is
895already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
896the argument is placed in the slot, filling it (even if the expression is
897``None``, it fills the slot). When all arguments have been processed, the slots
898that are still unfilled are filled with the corresponding default value from the
899function definition. (Default values are calculated, once, when the function is
900defined; thus, a mutable object such as a list or dictionary used as default
901value will be shared by all calls that don't specify an argument value for the
902corresponding slot; this should usually be avoided.) If there are any unfilled
903slots for which no default value is specified, a :exc:`TypeError` exception is
904raised. Otherwise, the list of filled slots is used as the argument list for
905the call.
906
Georg Brandl495f7b52009-10-27 15:28:25 +0000907.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000908
Georg Brandl495f7b52009-10-27 15:28:25 +0000909 An implementation may provide built-in functions whose positional parameters
910 do not have names, even if they are 'named' for the purpose of documentation,
911 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000912 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000913 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000914
Georg Brandl116aa622007-08-15 14:28:22 +0000915If there are more positional arguments than there are formal parameter slots, a
916:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
917``*identifier`` is present; in this case, that formal parameter receives a tuple
918containing the excess positional arguments (or an empty tuple if there were no
919excess positional arguments).
920
921If any keyword argument does not correspond to a formal parameter name, a
922:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
923``**identifier`` is present; in this case, that formal parameter receives a
924dictionary containing the excess keyword arguments (using the keywords as keys
925and the argument values as corresponding values), or a (new) empty dictionary if
926there were no excess keyword arguments.
927
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300928.. index::
929 single: *; in function calls
Martin Panter0c0da482016-06-12 01:46:50 +0000930 single: unpacking; in function calls
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300931
Georg Brandl116aa622007-08-15 14:28:22 +0000932If the syntax ``*expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +0000933evaluate to an :term:`iterable`. Elements from these iterables are
934treated as if they were additional positional arguments. For the call
935``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*,
936this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
937*y1*, ..., *yM*, *x3*, *x4*.
Georg Brandl116aa622007-08-15 14:28:22 +0000938
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000939A consequence of this is that although the ``*expression`` syntax may appear
Martin Panter0c0da482016-06-12 01:46:50 +0000940*after* explicit keyword arguments, it is processed *before* the
941keyword arguments (and any ``**expression`` arguments -- see below). So::
Georg Brandl116aa622007-08-15 14:28:22 +0000942
943 >>> def f(a, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300944 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000945 ...
946 >>> f(b=1, *(2,))
947 2 1
948 >>> f(a=1, *(2,))
949 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530950 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000951 TypeError: f() got multiple values for keyword argument 'a'
952 >>> f(1, *(2,))
953 1 2
954
955It is unusual for both keyword arguments and the ``*expression`` syntax to be
956used in the same call, so in practice this confusion does not arise.
957
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300958.. index::
959 single: **; in function calls
960
Georg Brandl116aa622007-08-15 14:28:22 +0000961If the syntax ``**expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +0000962evaluate to a :term:`mapping`, the contents of which are treated as
963additional keyword arguments. If a keyword is already present
964(as an explicit keyword argument, or from another unpacking),
965a :exc:`TypeError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000966
967Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
968used as positional argument slots or as keyword argument names.
969
Martin Panter0c0da482016-06-12 01:46:50 +0000970.. versionchanged:: 3.5
971 Function calls accept any number of ``*`` and ``**`` unpackings,
972 positional arguments may follow iterable unpackings (``*``),
973 and keyword arguments may follow dictionary unpackings (``**``).
974 Originally proposed by :pep:`448`.
975
Georg Brandl116aa622007-08-15 14:28:22 +0000976A call always returns some value, possibly ``None``, unless it raises an
977exception. How this value is computed depends on the type of the callable
978object.
979
980If it is---
981
982a user-defined function:
983 .. index::
984 pair: function; call
985 triple: user-defined; function; call
986 object: user-defined function
987 object: function
988
989 The code block for the function is executed, passing it the argument list. The
990 first thing the code block will do is bind the formal parameters to the
991 arguments; this is described in section :ref:`function`. When the code block
992 executes a :keyword:`return` statement, this specifies the return value of the
993 function call.
994
995a built-in function or method:
996 .. index::
997 pair: function; call
998 pair: built-in function; call
999 pair: method; call
1000 pair: built-in method; call
1001 object: built-in method
1002 object: built-in function
1003 object: method
1004 object: function
1005
1006 The result is up to the interpreter; see :ref:`built-in-funcs` for the
1007 descriptions of built-in functions and methods.
1008
1009a class object:
1010 .. index::
1011 object: class
1012 pair: class object; call
1013
1014 A new instance of that class is returned.
1015
1016a class instance method:
1017 .. index::
1018 object: class instance
1019 object: instance
1020 pair: class instance; call
1021
1022 The corresponding user-defined function is called, with an argument list that is
1023 one longer than the argument list of the call: the instance becomes the first
1024 argument.
1025
1026a class instance:
1027 .. index::
1028 pair: instance; call
1029 single: __call__() (object method)
1030
1031 The class must define a :meth:`__call__` method; the effect is then the same as
1032 if that method was called.
1033
1034
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001035.. _await:
1036
1037Await expression
1038================
1039
1040Suspend the execution of :term:`coroutine` on an :term:`awaitable` object.
1041Can only be used inside a :term:`coroutine function`.
1042
1043.. productionlist::
Serhiy Storchakac7cc9852016-05-08 21:59:46 +03001044 await_expr: "await" `primary`
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001045
1046.. versionadded:: 3.5
1047
1048
Georg Brandl116aa622007-08-15 14:28:22 +00001049.. _power:
1050
1051The power operator
1052==================
1053
1054The power operator binds more tightly than unary operators on its left; it binds
1055less tightly than unary operators on its right. The syntax is:
1056
1057.. productionlist::
Serhiy Storchakac7cc9852016-05-08 21:59:46 +03001058 power: ( `await_expr` | `primary` ) ["**" `u_expr`]
Georg Brandl116aa622007-08-15 14:28:22 +00001059
1060Thus, in an unparenthesized sequence of power and unary operators, the operators
1061are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +00001062for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001063
1064The power operator has the same semantics as the built-in :func:`pow` function,
1065when called with two arguments: it yields its left argument raised to the power
1066of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +00001067type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +00001068
Georg Brandl96593ed2007-09-07 14:15:41 +00001069For int operands, the result has the same type as the operands unless the second
1070argument is negative; in that case, all arguments are converted to float and a
1071float result is delivered. For example, ``10**2`` returns ``100``, but
1072``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +00001073
1074Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +00001075Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001076number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001077
1078
1079.. _unary:
1080
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001081Unary arithmetic and bitwise operations
1082=======================================
Georg Brandl116aa622007-08-15 14:28:22 +00001083
1084.. index::
1085 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +00001086 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001087
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001088All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +00001089
1090.. productionlist::
1091 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
1092
1093.. index::
1094 single: negation
1095 single: minus
1096
1097The unary ``-`` (minus) operator yields the negation of its numeric argument.
1098
1099.. index:: single: plus
1100
1101The unary ``+`` (plus) operator yields its numeric argument unchanged.
1102
1103.. index:: single: inversion
1104
Christian Heimesfaf2f632008-01-06 16:59:19 +00001105
Georg Brandl95817b32008-05-11 14:30:18 +00001106The unary ``~`` (invert) operator yields the bitwise inversion of its integer
1107argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
1108applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00001109
1110.. index:: exception: TypeError
1111
1112In all three cases, if the argument does not have the proper type, a
1113:exc:`TypeError` exception is raised.
1114
1115
1116.. _binary:
1117
1118Binary arithmetic operations
1119============================
1120
1121.. index:: triple: binary; arithmetic; operation
1122
1123The binary arithmetic operations have the conventional priority levels. Note
1124that some of these operations also apply to certain non-numeric types. Apart
1125from the power operator, there are only two levels, one for multiplicative
1126operators and one for additive operators:
1127
1128.. productionlist::
Benjamin Petersond51374e2014-04-09 23:55:56 -04001129 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
1130 : `m_expr` "//" `u_expr`| `m_expr` "/" `u_expr` |
1131 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001132 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
1133
1134.. index:: single: multiplication
1135
1136The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +00001137arguments must either both be numbers, or one argument must be an integer and
1138the other must be a sequence. In the former case, the numbers are converted to a
1139common type and then multiplied together. In the latter case, sequence
1140repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001141
Andrés Delfino69511862018-06-15 16:23:00 -03001142.. index::
1143 single: matrix multiplication
1144 operator: @
Benjamin Petersond51374e2014-04-09 23:55:56 -04001145
1146The ``@`` (at) operator is intended to be used for matrix multiplication. No
1147builtin Python types implement this operator.
1148
1149.. versionadded:: 3.5
1150
Georg Brandl116aa622007-08-15 14:28:22 +00001151.. index::
1152 exception: ZeroDivisionError
1153 single: division
1154
1155The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
1156their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +02001157Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +00001158integer; the result is that of mathematical division with the 'floor' function
1159applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
1160exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001161
1162.. index:: single: modulo
1163
1164The ``%`` (modulo) operator yields the remainder from the division of the first
1165argument by the second. The numeric arguments are first converted to a common
1166type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
1167arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
1168(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
1169result with the same sign as its second operand (or zero); the absolute value of
1170the result is strictly smaller than the absolute value of the second operand
1171[#]_.
1172
Georg Brandl96593ed2007-09-07 14:15:41 +00001173The floor division and modulo operators are connected by the following
1174identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
1175connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
1176x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +00001177
1178In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +00001179also overloaded by string objects to perform old-style string formatting (also
1180known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +00001181Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +00001182
1183The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +00001184function are not defined for complex numbers. Instead, convert to a floating
1185point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +00001186
1187.. index:: single: addition
1188
Georg Brandl96593ed2007-09-07 14:15:41 +00001189The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001190must either both be numbers or both be sequences of the same type. In the
1191former case, the numbers are converted to a common type and then added together.
1192In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +00001193
1194.. index:: single: subtraction
1195
1196The ``-`` (subtraction) operator yields the difference of its arguments. The
1197numeric arguments are first converted to a common type.
1198
1199
1200.. _shifting:
1201
1202Shifting operations
1203===================
1204
1205.. index:: pair: shifting; operation
1206
1207The shifting operations have lower priority than the arithmetic operations:
1208
1209.. productionlist::
1210 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
1211
Georg Brandl96593ed2007-09-07 14:15:41 +00001212These operators accept integers as arguments. They shift the first argument to
1213the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001214
1215.. index:: exception: ValueError
1216
Georg Brandl0aaae262013-10-08 21:47:18 +02001217A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
1218shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001219
1220
1221.. _bitwise:
1222
Christian Heimesfaf2f632008-01-06 16:59:19 +00001223Binary bitwise operations
1224=========================
Georg Brandl116aa622007-08-15 14:28:22 +00001225
Christian Heimesfaf2f632008-01-06 16:59:19 +00001226.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001227
1228Each of the three bitwise operations has a different priority level:
1229
1230.. productionlist::
1231 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1232 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1233 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1234
Christian Heimesfaf2f632008-01-06 16:59:19 +00001235.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +00001236
Georg Brandl96593ed2007-09-07 14:15:41 +00001237The ``&`` operator yields the bitwise AND of its arguments, which must be
1238integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001239
1240.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001241 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001242 pair: exclusive; or
1243
1244The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001245must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001246
1247.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001248 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001249 pair: inclusive; or
1250
1251The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001252must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001253
1254
1255.. _comparisons:
1256
1257Comparisons
1258===========
1259
1260.. index:: single: comparison
1261
1262.. index:: pair: C; language
1263
1264Unlike C, all comparison operations in Python have the same priority, which is
1265lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1266C, expressions like ``a < b < c`` have the interpretation that is conventional
1267in mathematics:
1268
1269.. productionlist::
1270 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1271 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1272 : | "is" ["not"] | ["not"] "in"
1273
1274Comparisons yield boolean values: ``True`` or ``False``.
1275
1276.. index:: pair: chaining; comparisons
1277
1278Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1279``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1280cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1281
Guido van Rossum04110fb2007-08-24 16:32:05 +00001282Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1283*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1284to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1285evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001286
Guido van Rossum04110fb2007-08-24 16:32:05 +00001287Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001288*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1289pretty).
1290
Martin Panteraa0da862015-09-23 05:28:13 +00001291Value comparisons
1292-----------------
1293
Georg Brandl116aa622007-08-15 14:28:22 +00001294The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
Martin Panteraa0da862015-09-23 05:28:13 +00001295values of two objects. The objects do not need to have the same type.
Georg Brandl116aa622007-08-15 14:28:22 +00001296
Martin Panteraa0da862015-09-23 05:28:13 +00001297Chapter :ref:`objects` states that objects have a value (in addition to type
1298and identity). The value of an object is a rather abstract notion in Python:
1299For example, there is no canonical access method for an object's value. Also,
1300there is no requirement that the value of an object should be constructed in a
1301particular way, e.g. comprised of all its data attributes. Comparison operators
1302implement a particular notion of what the value of an object is. One can think
1303of them as defining the value of an object indirectly, by means of their
1304comparison implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00001305
Martin Panteraa0da862015-09-23 05:28:13 +00001306Because all types are (direct or indirect) subtypes of :class:`object`, they
1307inherit the default comparison behavior from :class:`object`. Types can
1308customize their comparison behavior by implementing
1309:dfn:`rich comparison methods` like :meth:`__lt__`, described in
1310:ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001311
Martin Panteraa0da862015-09-23 05:28:13 +00001312The default behavior for equality comparison (``==`` and ``!=``) is based on
1313the identity of the objects. Hence, equality comparison of instances with the
1314same identity results in equality, and equality comparison of instances with
1315different identities results in inequality. A motivation for this default
1316behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1317implies ``x == y``).
1318
1319A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1320an attempt raises :exc:`TypeError`. A motivation for this default behavior is
1321the lack of a similar invariant as for equality.
1322
1323The behavior of the default equality comparison, that instances with different
1324identities are always unequal, may be in contrast to what types will need that
1325have a sensible definition of object value and value-based equality. Such
1326types will need to customize their comparison behavior, and in fact, a number
1327of built-in types have done that.
1328
1329The following list describes the comparison behavior of the most important
1330built-in types.
1331
1332* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1333 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
1334 compared within and across their types, with the restriction that complex
1335 numbers do not support order comparison. Within the limits of the types
1336 involved, they compare mathematically (algorithmically) correct without loss
1337 of precision.
1338
1339 The not-a-number values :const:`float('NaN')` and :const:`Decimal('NaN')`
1340 are special. They are identical to themselves (``x is x`` is true) but
1341 are not equal to themselves (``x == x`` is false). Additionally,
1342 comparing any number to a not-a-number value
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001343 will return ``False``. For example, both ``3 < float('NaN')`` and
1344 ``float('NaN') < 3`` will return ``False``.
1345
Martin Panteraa0da862015-09-23 05:28:13 +00001346* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
1347 compared within and across their types. They compare lexicographically using
1348 the numeric values of their elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001349
Martin Panteraa0da862015-09-23 05:28:13 +00001350* Strings (instances of :class:`str`) compare lexicographically using the
1351 numerical Unicode code points (the result of the built-in function
1352 :func:`ord`) of their characters. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001353
Martin Panteraa0da862015-09-23 05:28:13 +00001354 Strings and binary sequences cannot be directly compared.
Georg Brandl116aa622007-08-15 14:28:22 +00001355
Martin Panteraa0da862015-09-23 05:28:13 +00001356* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can
1357 be compared only within each of their types, with the restriction that ranges
1358 do not support order comparison. Equality comparison across these types
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +02001359 results in inequality, and ordering comparison across these types raises
Martin Panteraa0da862015-09-23 05:28:13 +00001360 :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001361
Martin Panteraa0da862015-09-23 05:28:13 +00001362 Sequences compare lexicographically using comparison of corresponding
1363 elements, whereby reflexivity of the elements is enforced.
Georg Brandl116aa622007-08-15 14:28:22 +00001364
Martin Panteraa0da862015-09-23 05:28:13 +00001365 In enforcing reflexivity of elements, the comparison of collections assumes
1366 that for a collection element ``x``, ``x == x`` is always true. Based on
1367 that assumption, element identity is compared first, and element comparison
1368 is performed only for distinct elements. This approach yields the same
1369 result as a strict element comparison would, if the compared elements are
1370 reflexive. For non-reflexive elements, the result is different than for
1371 strict element comparison, and may be surprising: The non-reflexive
1372 not-a-number values for example result in the following comparison behavior
1373 when used in a list::
1374
1375 >>> nan = float('NaN')
1376 >>> nan is nan
1377 True
1378 >>> nan == nan
1379 False <-- the defined non-reflexive behavior of NaN
1380 >>> [nan] == [nan]
1381 True <-- list enforces reflexivity and tests identity first
1382
1383 Lexicographical comparison between built-in collections works as follows:
1384
1385 - For two collections to compare equal, they must be of the same type, have
1386 the same length, and each pair of corresponding elements must compare
1387 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1388 same).
1389
1390 - Collections that support order comparison are ordered the same as their
1391 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same
1392 value as ``x <= y``). If a corresponding element does not exist, the
1393 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1394 true).
1395
1396* Mappings (instances of :class:`dict`) compare equal if and only if they have
cocoatomocdcac032017-03-31 14:48:49 +09001397 equal `(key, value)` pairs. Equality comparison of the keys and values
Martin Panteraa0da862015-09-23 05:28:13 +00001398 enforces reflexivity.
1399
1400 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
1401
1402* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within
1403 and across their types.
1404
1405 They define order
1406 comparison operators to mean subset and superset tests. Those relations do
1407 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}``
1408 are not equal, nor subsets of one another, nor supersets of one
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001409 another). Accordingly, sets are not appropriate arguments for functions
Martin Panteraa0da862015-09-23 05:28:13 +00001410 which depend on total ordering (for example, :func:`min`, :func:`max`, and
1411 :func:`sorted` produce undefined results given a list of sets as inputs).
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001412
Martin Panteraa0da862015-09-23 05:28:13 +00001413 Comparison of sets enforces reflexivity of its elements.
Georg Brandl116aa622007-08-15 14:28:22 +00001414
Martin Panteraa0da862015-09-23 05:28:13 +00001415* Most other built-in types have no comparison methods implemented, so they
1416 inherit the default comparison behavior.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001417
Martin Panteraa0da862015-09-23 05:28:13 +00001418User-defined classes that customize their comparison behavior should follow
1419some consistency rules, if possible:
1420
1421* Equality comparison should be reflexive.
1422 In other words, identical objects should compare equal:
1423
1424 ``x is y`` implies ``x == y``
1425
1426* Comparison should be symmetric.
1427 In other words, the following expressions should have the same result:
1428
1429 ``x == y`` and ``y == x``
1430
1431 ``x != y`` and ``y != x``
1432
1433 ``x < y`` and ``y > x``
1434
1435 ``x <= y`` and ``y >= x``
1436
1437* Comparison should be transitive.
1438 The following (non-exhaustive) examples illustrate that:
1439
1440 ``x > y and y > z`` implies ``x > z``
1441
1442 ``x < y and y <= z`` implies ``x < z``
1443
1444* Inverse comparison should result in the boolean negation.
1445 In other words, the following expressions should have the same result:
1446
1447 ``x == y`` and ``not x != y``
1448
1449 ``x < y`` and ``not x >= y`` (for total ordering)
1450
1451 ``x > y`` and ``not x <= y`` (for total ordering)
1452
1453 The last two expressions apply to totally ordered collections (e.g. to
1454 sequences, but not to sets or mappings). See also the
1455 :func:`~functools.total_ordering` decorator.
1456
Martin Panter8dbb0ca2017-01-29 10:00:23 +00001457* The :func:`hash` result should be consistent with equality.
1458 Objects that are equal should either have the same hash value,
1459 or be marked as unhashable.
1460
Martin Panteraa0da862015-09-23 05:28:13 +00001461Python does not enforce these consistency rules. In fact, the not-a-number
1462values are an example for not following these rules.
1463
1464
1465.. _in:
1466.. _not in:
Georg Brandl495f7b52009-10-27 15:28:25 +00001467.. _membership-test-details:
1468
Martin Panteraa0da862015-09-23 05:28:13 +00001469Membership test operations
1470--------------------------
1471
Georg Brandl96593ed2007-09-07 14:15:41 +00001472The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301473s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
1474``x not in s`` returns the negation of ``x in s``. All built-in sequences and
1475set types support this as well as dictionary, for which :keyword:`in` tests
1476whether the dictionary has a given key. For container types such as list, tuple,
1477set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001478to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001479
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301480For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
Georg Brandl4b491312007-08-31 09:22:56 +00001481substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1482always considered to be a substring of any other string, so ``"" in "abc"`` will
1483return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001484
Georg Brandl116aa622007-08-15 14:28:22 +00001485For user-defined classes which define the :meth:`__contains__` method, ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301486y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and
1487``False`` otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001488
Georg Brandl495f7b52009-10-27 15:28:25 +00001489For user-defined classes which do not define :meth:`__contains__` but do define
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301490:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z`` with ``x == z`` is
Georg Brandl495f7b52009-10-27 15:28:25 +00001491produced while iterating over ``y``. If an exception is raised during the
1492iteration, it is as if :keyword:`in` raised that exception.
1493
1494Lastly, the old-style iteration protocol is tried: if a class defines
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301495:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
Georg Brandl116aa622007-08-15 14:28:22 +00001496integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001497raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001498if :keyword:`in` raised that exception).
1499
1500.. index::
1501 operator: in
1502 operator: not in
1503 pair: membership; test
1504 object: sequence
1505
1506The operator :keyword:`not in` is defined to have the inverse true value of
1507:keyword:`in`.
1508
1509.. index::
1510 operator: is
1511 operator: is not
1512 pair: identity; test
1513
Martin Panteraa0da862015-09-23 05:28:13 +00001514
1515.. _is:
1516.. _is not:
1517
1518Identity comparisons
1519--------------------
1520
Georg Brandl116aa622007-08-15 14:28:22 +00001521The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
Raymond Hettinger06e18a72016-09-11 17:23:49 -07001522is y`` is true if and only if *x* and *y* are the same object. Object identity
1523is determined using the :meth:`id` function. ``x is not y`` yields the inverse
1524truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001525
1526
1527.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001528.. _and:
1529.. _or:
1530.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001531
1532Boolean operations
1533==================
1534
1535.. index::
1536 pair: Conditional; expression
1537 pair: Boolean; operation
1538
Georg Brandl116aa622007-08-15 14:28:22 +00001539.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001540 or_test: `and_test` | `or_test` "or" `and_test`
1541 and_test: `not_test` | `and_test` "and" `not_test`
1542 not_test: `comparison` | "not" `not_test`
1543
1544In the context of Boolean operations, and also when expressions are used by
1545control flow statements, the following values are interpreted as false:
1546``False``, ``None``, numeric zero of all types, and empty strings and containers
1547(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001548other values are interpreted as true. User-defined objects can customize their
1549truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001550
1551.. index:: operator: not
1552
1553The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1554otherwise.
1555
Georg Brandl116aa622007-08-15 14:28:22 +00001556.. index:: operator: and
1557
1558The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1559returned; otherwise, *y* is evaluated and the resulting value is returned.
1560
1561.. index:: operator: or
1562
1563The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1564returned; otherwise, *y* is evaluated and the resulting value is returned.
1565
1566(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1567they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001568argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001569replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001570the desired value. Because :keyword:`not` has to create a new value, it
1571returns a boolean value regardless of the type of its argument
1572(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001573
1574
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001575Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001576=======================
1577
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001578.. index::
1579 pair: conditional; expression
1580 pair: ternary; operator
1581
1582.. productionlist::
1583 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001584 expression: `conditional_expression` | `lambda_expr`
1585 expression_nocond: `or_test` | `lambda_expr_nocond`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001586
1587Conditional expressions (sometimes called a "ternary operator") have the lowest
1588priority of all Python operations.
1589
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001590The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1591If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001592evaluated and its value is returned.
1593
1594See :pep:`308` for more details about conditional expressions.
1595
1596
Georg Brandl116aa622007-08-15 14:28:22 +00001597.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001598.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001599
1600Lambdas
1601=======
1602
1603.. index::
1604 pair: lambda; expression
1605 pair: lambda; form
1606 pair: anonymous; function
1607
1608.. productionlist::
Georg Brandl242e6a02013-10-06 10:28:39 +02001609 lambda_expr: "lambda" [`parameter_list`]: `expression`
1610 lambda_expr_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001611
Zachary Ware2f78b842014-06-03 09:32:40 -05001612Lambda expressions (sometimes called lambda forms) are used to create anonymous
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001613functions. The expression ``lambda parameters: expression`` yields a function
Martin Panter1050d2d2016-07-26 11:18:21 +02001614object. The unnamed object behaves like a function object defined with:
1615
1616.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +00001617
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001618 def <lambda>(parameters):
Georg Brandl116aa622007-08-15 14:28:22 +00001619 return expression
1620
1621See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001622functions created with lambda expressions cannot contain statements or
1623annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001624
Georg Brandl116aa622007-08-15 14:28:22 +00001625
1626.. _exprlists:
1627
1628Expression lists
1629================
1630
1631.. index:: pair: expression; list
1632
1633.. productionlist::
1634 expression_list: `expression` ( "," `expression` )* [","]
Martin Panter0c0da482016-06-12 01:46:50 +00001635 starred_list: `starred_item` ( "," `starred_item` )* [","]
1636 starred_expression: `expression` | ( `starred_item` "," )* [`starred_item`]
1637 starred_item: `expression` | "*" `or_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001638
1639.. index:: object: tuple
1640
Martin Panter0c0da482016-06-12 01:46:50 +00001641Except when part of a list or set display, an expression list
1642containing at least one comma yields a tuple. The length of
Georg Brandl116aa622007-08-15 14:28:22 +00001643the tuple is the number of expressions in the list. The expressions are
1644evaluated from left to right.
1645
Martin Panter0c0da482016-06-12 01:46:50 +00001646.. index::
1647 pair: iterable; unpacking
1648 single: *; in expression lists
1649
1650An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be
1651an :term:`iterable`. The iterable is expanded into a sequence of items,
1652which are included in the new tuple, list, or set, at the site of
1653the unpacking.
1654
1655.. versionadded:: 3.5
1656 Iterable unpacking in expression lists, originally proposed by :pep:`448`.
1657
Georg Brandl116aa622007-08-15 14:28:22 +00001658.. index:: pair: trailing; comma
1659
1660The trailing comma is required only to create a single tuple (a.k.a. a
1661*singleton*); it is optional in all other cases. A single expression without a
1662trailing comma doesn't create a tuple, but rather yields the value of that
1663expression. (To create an empty tuple, use an empty pair of parentheses:
1664``()``.)
1665
1666
1667.. _evalorder:
1668
1669Evaluation order
1670================
1671
1672.. index:: pair: evaluation; order
1673
Georg Brandl96593ed2007-09-07 14:15:41 +00001674Python evaluates expressions from left to right. Notice that while evaluating
1675an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001676
1677In the following lines, expressions will be evaluated in the arithmetic order of
1678their suffixes::
1679
1680 expr1, expr2, expr3, expr4
1681 (expr1, expr2, expr3, expr4)
1682 {expr1: expr2, expr3: expr4}
1683 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001684 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001685 expr3, expr4 = expr1, expr2
1686
1687
1688.. _operator-summary:
1689
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001690Operator precedence
1691===================
Georg Brandl116aa622007-08-15 14:28:22 +00001692
1693.. index:: pair: operator; precedence
1694
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001695The following table summarizes the operator precedence in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001696precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001697the same box have the same precedence. Unless the syntax is explicitly given,
1698operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001699exponentiation, which groups from right to left).
1700
1701Note that comparisons, membership tests, and identity tests, all have the same
1702precedence and have a left-to-right chaining feature as described in the
1703:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001704
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001705
1706+-----------------------------------------------+-------------------------------------+
1707| Operator | Description |
1708+===============================================+=====================================+
1709| :keyword:`lambda` | Lambda expression |
1710+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001711| :keyword:`if` -- :keyword:`else` | Conditional expression |
1712+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001713| :keyword:`or` | Boolean OR |
1714+-----------------------------------------------+-------------------------------------+
1715| :keyword:`and` | Boolean AND |
1716+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001717| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001718+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001719| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001720| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001721| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001722+-----------------------------------------------+-------------------------------------+
1723| ``|`` | Bitwise OR |
1724+-----------------------------------------------+-------------------------------------+
1725| ``^`` | Bitwise XOR |
1726+-----------------------------------------------+-------------------------------------+
1727| ``&`` | Bitwise AND |
1728+-----------------------------------------------+-------------------------------------+
1729| ``<<``, ``>>`` | Shifts |
1730+-----------------------------------------------+-------------------------------------+
1731| ``+``, ``-`` | Addition and subtraction |
1732+-----------------------------------------------+-------------------------------------+
Benjamin Petersond51374e2014-04-09 23:55:56 -04001733| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
svelankar9b47af62017-09-17 20:56:16 -04001734| | multiplication, division, floor |
1735| | division, remainder [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001736+-----------------------------------------------+-------------------------------------+
1737| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1738+-----------------------------------------------+-------------------------------------+
1739| ``**`` | Exponentiation [#]_ |
1740+-----------------------------------------------+-------------------------------------+
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001741| ``await`` ``x`` | Await expression |
1742+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001743| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1744| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1745+-----------------------------------------------+-------------------------------------+
1746| ``(expressions...)``, | Binding or tuple display, |
1747| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001748| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001749| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001750+-----------------------------------------------+-------------------------------------+
1751
Georg Brandl116aa622007-08-15 14:28:22 +00001752
1753.. rubric:: Footnotes
1754
Georg Brandl116aa622007-08-15 14:28:22 +00001755.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1756 true numerically due to roundoff. For example, and assuming a platform on which
1757 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1758 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001759 1e100``, which is numerically exactly equal to ``1e100``. The function
1760 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001761 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1762 is more appropriate depends on the application.
1763
1764.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001765 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001766 cases, Python returns the latter result, in order to preserve that
1767 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1768
Martin Panteraa0da862015-09-23 05:28:13 +00001769.. [#] The Unicode standard distinguishes between :dfn:`code points`
1770 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
1771 While most abstract characters in Unicode are only represented using one
1772 code point, there is a number of abstract characters that can in addition be
1773 represented using a sequence of more than one code point. For example, the
1774 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
1775 as a single :dfn:`precomposed character` at code position U+00C7, or as a
1776 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
1777 LETTER C), followed by a :dfn:`combining character` at code position U+0327
1778 (COMBINING CEDILLA).
1779
1780 The comparison operators on strings compare at the level of Unicode code
1781 points. This may be counter-intuitive to humans. For example,
1782 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1783 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".
1784
1785 To compare strings at the level of abstract characters (that is, in a way
1786 intuitive to humans), use :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001787
Georg Brandl48310cd2009-01-03 21:18:54 +00001788.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001789 descriptors, you may notice seemingly unusual behaviour in certain uses of
1790 the :keyword:`is` operator, like those involving comparisons between instance
1791 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001792
Georg Brandl063f2372010-12-01 15:32:43 +00001793.. [#] The ``%`` operator is also used for string formatting; the same
1794 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001795
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001796.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1797 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.