blob: fb92ad0f07c21ed1f5c2bf9bb3505b3916b8db3c [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`
Yury Selivanov03660042016-12-15 17:36:05 -0500175 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
199nested scope (in Python 3.7, such expressions emit :exc:`DeprecationWarning`
200when compiled, in Python 3.8+ they will emit :exc:`SyntaxError`).
Georg Brandl02c30562007-09-07 17:52:53 +0000201
Yury Selivanov03660042016-12-15 17:36:05 -0500202Since Python 3.6, in an :keyword:`async def` function, an :keyword:`async for`
203clause may be used to iterate over a :term:`asynchronous iterator`.
204A comprehension in an :keyword:`async def` function may consist of either a
205:keyword:`for` or :keyword:`async for` clause following the leading
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +0200206expression, may contain additional :keyword:`for` or :keyword:`async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500207clauses, and may also use :keyword:`await` expressions.
208If a comprehension contains either :keyword:`async for` clauses
209or :keyword:`await` expressions it is called an
210:dfn:`asynchronous comprehension`. An asynchronous comprehension may
211suspend the execution of the coroutine function in which it appears.
212See also :pep:`530`.
Georg Brandl96593ed2007-09-07 14:15:41 +0000213
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200214.. versionadded:: 3.6
215 Asynchronous comprehensions were introduced.
216
217.. deprecated:: 3.7
218 ``yield`` and ``yield from`` deprecated in the implicitly nested scope.
219
220
Georg Brandl116aa622007-08-15 14:28:22 +0000221.. _lists:
222
223List displays
224-------------
225
226.. index::
227 pair: list; display
228 pair: list; comprehensions
Georg Brandl96593ed2007-09-07 14:15:41 +0000229 pair: empty; list
230 object: list
Georg Brandl116aa622007-08-15 14:28:22 +0000231
232A list display is a possibly empty series of expressions enclosed in square
233brackets:
234
235.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000236 list_display: "[" [`starred_list` | `comprehension`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000237
Georg Brandl96593ed2007-09-07 14:15:41 +0000238A list display yields a new list object, the contents being specified by either
239a list of expressions or a comprehension. When a comma-separated list of
240expressions is supplied, its elements are evaluated from left to right and
241placed into the list object in that order. When a comprehension is supplied,
242the list is constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244
Georg Brandl96593ed2007-09-07 14:15:41 +0000245.. _set:
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Georg Brandl96593ed2007-09-07 14:15:41 +0000247Set displays
248------------
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Georg Brandl96593ed2007-09-07 14:15:41 +0000250.. index:: pair: set; display
251 object: set
Georg Brandl116aa622007-08-15 14:28:22 +0000252
Georg Brandl96593ed2007-09-07 14:15:41 +0000253A set display is denoted by curly braces and distinguishable from dictionary
254displays by the lack of colons separating keys and values:
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000257 set_display: "{" (`starred_list` | `comprehension`) "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000258
Georg Brandl96593ed2007-09-07 14:15:41 +0000259A set display yields a new mutable set object, the contents being specified by
260either a sequence of expressions or a comprehension. When a comma-separated
261list of expressions is supplied, its elements are evaluated from left to right
262and added to the set object. When a comprehension is supplied, the set is
263constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
Georg Brandl528cdb12008-09-21 07:09:51 +0000265An empty set cannot be constructed with ``{}``; this literal constructs an empty
266dictionary.
Christian Heimes78644762008-03-04 23:39:23 +0000267
268
Georg Brandl116aa622007-08-15 14:28:22 +0000269.. _dict:
270
271Dictionary displays
272-------------------
273
274.. index:: pair: dictionary; display
Georg Brandl96593ed2007-09-07 14:15:41 +0000275 key, datum, key/datum pair
276 object: dictionary
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278A dictionary display is a possibly empty series of key/datum pairs enclosed in
279curly braces:
280
281.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000282 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000283 key_datum_list: `key_datum` ("," `key_datum`)* [","]
Martin Panter0c0da482016-06-12 01:46:50 +0000284 key_datum: `expression` ":" `expression` | "**" `or_expr`
Georg Brandl96593ed2007-09-07 14:15:41 +0000285 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287A dictionary display yields a new dictionary object.
288
Georg Brandl96593ed2007-09-07 14:15:41 +0000289If a comma-separated sequence of key/datum pairs is given, they are evaluated
290from left to right to define the entries of the dictionary: each key object is
291used as a key into the dictionary to store the corresponding datum. This means
292that you can specify the same key multiple times in the key/datum list, and the
293final dictionary's value for that key will be the last one given.
294
Martin Panter0c0da482016-06-12 01:46:50 +0000295.. index:: unpacking; dictionary, **; in dictionary displays
296
297A double asterisk ``**`` denotes :dfn:`dictionary unpacking`.
298Its operand must be a :term:`mapping`. Each mapping item is added
299to the new dictionary. Later values replace values already set by
300earlier key/datum pairs and earlier dictionary unpackings.
301
302.. versionadded:: 3.5
303 Unpacking into dictionary displays, originally proposed by :pep:`448`.
304
Georg Brandl96593ed2007-09-07 14:15:41 +0000305A dict comprehension, in contrast to list and set comprehensions, needs two
306expressions separated with a colon followed by the usual "for" and "if" clauses.
307When the comprehension is run, the resulting key and value elements are inserted
308in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
310.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000311 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000312
313Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000314:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000315all mutable objects.) Clashes between duplicate keys are not detected; the last
316datum (textually rightmost in the display) stored for a given key value
317prevails.
318
319
Georg Brandl96593ed2007-09-07 14:15:41 +0000320.. _genexpr:
321
322Generator expressions
323---------------------
324
325.. index:: pair: generator; expression
326 object: generator
327
328A generator expression is a compact generator notation in parentheses:
329
330.. productionlist::
331 generator_expression: "(" `expression` `comp_for` ")"
332
333A generator expression yields a new generator object. Its syntax is the same as
334for comprehensions, except that it is enclosed in parentheses instead of
335brackets or curly braces.
336
337Variables used in the generator expression are evaluated lazily when the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700338:meth:`~generator.__next__` method is called for the generator object (in the same
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200339fashion as normal generators). However, the iterable expression in the
340leftmost :keyword:`for` clause is immediately evaluated, so that an error
341produced by it will be emitted at the point where the generator expression
342is defined, rather than at the point where the first value is retrieved.
343Subsequent :keyword:`for` clauses and any filter condition in the leftmost
344:keyword:`for` clause cannot be evaluated in the enclosing scope as they may
345depend on the values obtained from the leftmost iterable. For example:
346``(x*y for x in range(10) for y in range(x, x+10))``.
Georg Brandl96593ed2007-09-07 14:15:41 +0000347
348The parentheses can be omitted on calls with only one argument. See section
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700349:ref:`calls` for details.
Georg Brandl96593ed2007-09-07 14:15:41 +0000350
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200351To avoid interfering with the expected operation of the generator expression
352itself, ``yield`` and ``yield from`` expressions are prohibited in the
353implicitly defined generator (in Python 3.7, such expressions emit
354:exc:`DeprecationWarning` when compiled, in Python 3.8+ they will emit
355:exc:`SyntaxError`).
356
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400357If a generator expression contains either :keyword:`async for`
358clauses or :keyword:`await` expressions it is called an
359:dfn:`asynchronous generator expression`. An asynchronous generator
360expression returns a new asynchronous generator object,
361which is an asynchronous iterator (see :ref:`async-iterators`).
362
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200363.. versionadded:: 3.6
364 Asynchronous generator expressions were introduced.
365
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400366.. versionchanged:: 3.7
367 Prior to Python 3.7, asynchronous generator expressions could
368 only appear in :keyword:`async def` coroutines. Starting
369 with 3.7, any function can use asynchronous generator expressions.
Georg Brandl96593ed2007-09-07 14:15:41 +0000370
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200371.. deprecated:: 3.7
372 ``yield`` and ``yield from`` deprecated in the implicitly nested scope.
373
374
Georg Brandl116aa622007-08-15 14:28:22 +0000375.. _yieldexpr:
376
377Yield expressions
378-----------------
379
380.. index::
381 keyword: yield
382 pair: yield; expression
383 pair: generator; function
384
385.. productionlist::
386 yield_atom: "(" `yield_expression` ")"
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000387 yield_expression: "yield" [`expression_list` | "from" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Yury Selivanov03660042016-12-15 17:36:05 -0500389The yield expression is used when defining a :term:`generator` function
390or an :term:`asynchronous generator` function and
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500391thus can only be used in the body of a function definition. Using a yield
Yury Selivanov03660042016-12-15 17:36:05 -0500392expression in a function's body causes that function to be a generator,
393and using it in an :keyword:`async def` function's body causes that
394coroutine function to be an asynchronous generator. For example::
395
396 def gen(): # defines a generator function
397 yield 123
398
399 async def agen(): # defines an asynchronous generator function (PEP 525)
400 yield 123
401
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200402Due to their side effects on the containing scope, ``yield`` expressions
403are not permitted as part of the implicitly defined scopes used to
404implement comprehensions and generator expressions (in Python 3.7, such
405expressions emit :exc:`DeprecationWarning` when compiled, in Python 3.8+
406they will emit :exc:`SyntaxError`)..
407
408.. deprecated:: 3.7
409 Yield expressions deprecated in the implicitly nested scopes used to
410 implement comprehensions and generator expressions.
411
Yury Selivanov03660042016-12-15 17:36:05 -0500412Generator functions are described below, while asynchronous generator
413functions are described separately in section
414:ref:`asynchronous-generator-functions`.
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416When a generator function is called, it returns an iterator known as a
Guido van Rossumd0150ad2015-05-05 12:02:01 -0700417generator. That generator then controls the execution of the generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000418The execution starts when one of the generator's methods is called. At that
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500419time, the execution proceeds to the first yield expression, where it is
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700420suspended again, returning the value of :token:`expression_list` to the generator's
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500421caller. By suspended, we mean that all local state is retained, including the
Ethan Furman2f825af2015-01-14 22:25:27 -0800422current bindings of local variables, the instruction pointer, the internal
423evaluation stack, and the state of any exception handling. When the execution
424is resumed by calling one of the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500425generator's methods, the function can proceed exactly as if the yield expression
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700426were just another external call. The value of the yield expression after
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500427resuming depends on the method which resumed the execution. If
428:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or
429the :func:`next` builtin) then the result is :const:`None`. Otherwise, if
430:meth:`~generator.send` is used, then the result will be the value passed in to
431that method.
Georg Brandl116aa622007-08-15 14:28:22 +0000432
433.. index:: single: coroutine
434
435All of this makes generator functions quite similar to coroutines; they yield
436multiple times, they have more than one entry point and their execution can be
437suspended. The only difference is that a generator function cannot control
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700438where the execution should continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000439transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000440
Ethan Furman2f825af2015-01-14 22:25:27 -0800441Yield expressions are allowed anywhere in a :keyword:`try` construct. If the
442generator is not resumed before it is
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500443finalized (by reaching a zero reference count or by being garbage collected),
444the generator-iterator's :meth:`~generator.close` method will be called,
445allowing any pending :keyword:`finally` clauses to execute.
Georg Brandl02c30562007-09-07 17:52:53 +0000446
Nick Coghlan0ed80192012-01-14 14:43:24 +1000447When ``yield from <expr>`` is used, it treats the supplied expression as
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000448a subiterator. All values produced by that subiterator are passed directly
449to the caller of the current generator's methods. Any values passed in with
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300450:meth:`~generator.send` and any exceptions passed in with
451:meth:`~generator.throw` are passed to the underlying iterator if it has the
452appropriate methods. If this is not the case, then :meth:`~generator.send`
453will raise :exc:`AttributeError` or :exc:`TypeError`, while
454:meth:`~generator.throw` will just raise the passed in exception immediately.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000455
456When the underlying iterator is complete, the :attr:`~StopIteration.value`
457attribute of the raised :exc:`StopIteration` instance becomes the value of
458the yield expression. It can be either set explicitly when raising
459:exc:`StopIteration`, or automatically when the sub-iterator is a generator
460(by returning a value from the sub-generator).
461
Nick Coghlan0ed80192012-01-14 14:43:24 +1000462 .. versionchanged:: 3.3
Martin Panterd21e0b52015-10-10 10:36:22 +0000463 Added ``yield from <expr>`` to delegate control flow to a subiterator.
Nick Coghlan0ed80192012-01-14 14:43:24 +1000464
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500465The parentheses may be omitted when the yield expression is the sole expression
466on the right hand side of an assignment statement.
467
468.. seealso::
469
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300470 :pep:`255` - Simple Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500471 The proposal for adding generators and the :keyword:`yield` statement to Python.
472
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300473 :pep:`342` - Coroutines via Enhanced Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500474 The proposal to enhance the API and syntax of generators, making them
475 usable as simple coroutines.
476
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300477 :pep:`380` - Syntax for Delegating to a Subgenerator
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500478 The proposal to introduce the :token:`yield_from` syntax, making delegation
479 to sub-generators easy.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000480
Georg Brandl116aa622007-08-15 14:28:22 +0000481.. index:: object: generator
Yury Selivanov66f88282015-06-24 11:04:15 -0400482.. _generator-methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000483
R David Murray2c1d1d62012-08-17 20:48:59 -0400484Generator-iterator methods
485^^^^^^^^^^^^^^^^^^^^^^^^^^
486
487This subsection describes the methods of a generator iterator. They can
488be used to control the execution of a generator function.
489
490Note that calling any of the generator methods below when the generator
491is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000492
493.. index:: exception: StopIteration
494
495
Georg Brandl96593ed2007-09-07 14:15:41 +0000496.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000497
Georg Brandl96593ed2007-09-07 14:15:41 +0000498 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500499 executed yield expression. When a generator function is resumed with a
500 :meth:`~generator.__next__` method, the current yield expression always
501 evaluates to :const:`None`. The execution then continues to the next yield
502 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300503 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500504 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000505 exception is raised.
506
507 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
508 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000509
510
511.. method:: generator.send(value)
512
513 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500514 *value* argument becomes the result of the current yield expression. The
515 :meth:`send` method returns the next value yielded by the generator, or
516 raises :exc:`StopIteration` if the generator exits without yielding another
517 value. When :meth:`send` is called to start the generator, it must be called
518 with :const:`None` as the argument, because there is no yield expression that
519 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521
522.. method:: generator.throw(type[, value[, traceback]])
523
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700524 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000525 and returns the next value yielded by the generator function. If the generator
526 exits without yielding another value, a :exc:`StopIteration` exception is
527 raised. If the generator function does not catch the passed-in exception, or
528 raises a different exception, then that exception propagates to the caller.
529
530.. index:: exception: GeneratorExit
531
532
533.. method:: generator.close()
534
535 Raises a :exc:`GeneratorExit` at the point where the generator function was
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400536 paused. If the generator function then exits gracefully, is already closed,
537 or raises :exc:`GeneratorExit` (by not catching the exception), close
538 returns to its caller. If the generator yields a value, a
539 :exc:`RuntimeError` is raised. If the generator raises any other exception,
540 it is propagated to the caller. :meth:`close` does nothing if the generator
541 has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000542
Chris Jerdonek2654b862012-12-23 15:31:57 -0800543.. index:: single: yield; examples
544
545Examples
546^^^^^^^^
547
Georg Brandl116aa622007-08-15 14:28:22 +0000548Here is a simple example that demonstrates the behavior of generators and
549generator functions::
550
551 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000552 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000553 ... try:
554 ... while True:
555 ... try:
556 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000557 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000558 ... value = e
559 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000560 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000561 ...
562 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000563 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000564 Execution starts when 'next()' is called for the first time.
565 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000566 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000567 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000568 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000569 2
570 >>> generator.throw(TypeError, "spam")
571 TypeError('spam',)
572 >>> generator.close()
573 Don't forget to clean up when 'close()' is called.
574
Chris Jerdonek2654b862012-12-23 15:31:57 -0800575For examples using ``yield from``, see :ref:`pep-380` in "What's New in
576Python."
577
Yury Selivanov03660042016-12-15 17:36:05 -0500578.. _asynchronous-generator-functions:
579
580Asynchronous generator functions
581^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
582
583The presence of a yield expression in a function or method defined using
584:keyword:`async def` further defines the function as a
585:term:`asynchronous generator` function.
586
587When an asynchronous generator function is called, it returns an
588asynchronous iterator known as an asynchronous generator object.
589That object then controls the execution of the generator function.
590An asynchronous generator object is typically used in an
591:keyword:`async for` statement in a coroutine function analogously to
592how a generator object would be used in a :keyword:`for` statement.
593
594Calling one of the asynchronous generator's methods returns an
595:term:`awaitable` object, and the execution starts when this object
596is awaited on. At that time, the execution proceeds to the first yield
597expression, where it is suspended again, returning the value of
598:token:`expression_list` to the awaiting coroutine. As with a generator,
599suspension means that all local state is retained, including the
600current bindings of local variables, the instruction pointer, the internal
601evaluation stack, and the state of any exception handling. When the execution
602is resumed by awaiting on the next object returned by the asynchronous
603generator's methods, the function can proceed exactly as if the yield
604expression were just another external call. The value of the yield expression
605after resuming depends on the method which resumed the execution. If
606:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
607:meth:`~agen.asend` is used, then the result will be the value passed in to
608that method.
609
610In an asynchronous generator function, yield expressions are allowed anywhere
611in a :keyword:`try` construct. However, if an asynchronous generator is not
612resumed before it is finalized (by reaching a zero reference count or by
613being garbage collected), then a yield expression within a :keyword:`try`
614construct could result in a failure to execute pending :keyword:`finally`
615clauses. In this case, it is the responsibility of the event loop or
616scheduler running the asynchronous generator to call the asynchronous
617generator-iterator's :meth:`~agen.aclose` method and run the resulting
618coroutine object, thus allowing any pending :keyword:`finally` clauses
619to execute.
620
621To take care of finalization, an event loop should define
622a *finalizer* function which takes an asynchronous generator-iterator
623and presumably calls :meth:`~agen.aclose` and executes the coroutine.
624This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`.
625When first iterated over, an asynchronous generator-iterator will store the
626registered *finalizer* to be called upon finalization. For a reference example
627of a *finalizer* method see the implementation of
628``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`.
629
630The expression ``yield from <expr>`` is a syntax error when used in an
631asynchronous generator function.
632
633.. index:: object: asynchronous-generator
634.. _asynchronous-generator-methods:
635
636Asynchronous generator-iterator methods
637^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
638
639This subsection describes the methods of an asynchronous generator iterator,
640which are used to control the execution of a generator function.
641
642
643.. index:: exception: StopAsyncIteration
644
645.. coroutinemethod:: agen.__anext__()
646
647 Returns an awaitable which when run starts to execute the asynchronous
648 generator or resumes it at the last executed yield expression. When an
649 asynchronous generator function is resumed with a :meth:`~agen.__anext__`
650 method, the current yield expression always evaluates to :const:`None` in
651 the returned awaitable, which when run will continue to the next yield
652 expression. The value of the :token:`expression_list` of the yield
653 expression is the value of the :exc:`StopIteration` exception raised by
654 the completing coroutine. If the asynchronous generator exits without
655 yielding another value, the awaitable instead raises an
656 :exc:`StopAsyncIteration` exception, signalling that the asynchronous
657 iteration has completed.
658
659 This method is normally called implicitly by a :keyword:`async for` loop.
660
661
662.. coroutinemethod:: agen.asend(value)
663
664 Returns an awaitable which when run resumes the execution of the
665 asynchronous generator. As with the :meth:`~generator.send()` method for a
666 generator, this "sends" a value into the asynchronous generator function,
667 and the *value* argument becomes the result of the current yield expression.
668 The awaitable returned by the :meth:`asend` method will return the next
669 value yielded by the generator as the value of the raised
670 :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the
671 asynchronous generator exits without yielding another value. When
672 :meth:`asend` is called to start the asynchronous
673 generator, it must be called with :const:`None` as the argument,
674 because there is no yield expression that could receive the value.
675
676
677.. coroutinemethod:: agen.athrow(type[, value[, traceback]])
678
679 Returns an awaitable that raises an exception of type ``type`` at the point
680 where the asynchronous generator was paused, and returns the next value
681 yielded by the generator function as the value of the raised
682 :exc:`StopIteration` exception. If the asynchronous generator exits
683 without yielding another value, an :exc:`StopAsyncIteration` exception is
684 raised by the awaitable.
685 If the generator function does not catch the passed-in exception, or
delirious-lettuce3378b202017-05-19 14:37:57 -0600686 raises a different exception, then when the awaitable is run that exception
Yury Selivanov03660042016-12-15 17:36:05 -0500687 propagates to the caller of the awaitable.
688
689.. index:: exception: GeneratorExit
690
691
692.. coroutinemethod:: agen.aclose()
693
694 Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
695 the asynchronous generator function at the point where it was paused.
696 If the asynchronous generator function then exits gracefully, is already
697 closed, or raises :exc:`GeneratorExit` (by not catching the exception),
698 then the returned awaitable will raise a :exc:`StopIteration` exception.
699 Any further awaitables returned by subsequent calls to the asynchronous
700 generator will raise a :exc:`StopAsyncIteration` exception. If the
701 asynchronous generator yields a value, a :exc:`RuntimeError` is raised
702 by the awaitable. If the asynchronous generator raises any other exception,
703 it is propagated to the caller of the awaitable. If the asynchronous
704 generator has already exited due to an exception or normal exit, then
705 further calls to :meth:`aclose` will return an awaitable that does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000706
Georg Brandl116aa622007-08-15 14:28:22 +0000707.. _primaries:
708
709Primaries
710=========
711
712.. index:: single: primary
713
714Primaries represent the most tightly bound operations of the language. Their
715syntax is:
716
717.. productionlist::
718 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
719
720
721.. _attribute-references:
722
723Attribute references
724--------------------
725
726.. index:: pair: attribute; reference
727
728An attribute reference is a primary followed by a period and a name:
729
730.. productionlist::
731 attributeref: `primary` "." `identifier`
732
733.. index::
734 exception: AttributeError
735 object: module
736 object: list
737
738The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000739references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700740attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500741overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700742the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
743the object produced is determined by the object. Multiple evaluations of the
744same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000745
746
747.. _subscriptions:
748
749Subscriptions
750-------------
751
752.. index:: single: subscription
753
754.. index::
755 object: sequence
756 object: mapping
757 object: string
758 object: tuple
759 object: list
760 object: dictionary
761 pair: sequence; item
762
763A subscription selects an item of a sequence (string, tuple or list) or mapping
764(dictionary) object:
765
766.. productionlist::
767 subscription: `primary` "[" `expression_list` "]"
768
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700769The primary must evaluate to an object that supports subscription (lists or
770dictionaries for example). User-defined objects can support subscription by
771defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000772
773For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000774
775If the primary is a mapping, the expression list must evaluate to an object
776whose value is one of the keys of the mapping, and the subscription selects the
777value in the mapping that corresponds to that key. (The expression list is a
778tuple except if it has exactly one item.)
779
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000780If the primary is a sequence, the expression (list) must evaluate to an integer
781or a slice (as discussed in the following section).
782
783The formal syntax makes no special provision for negative indices in
784sequences; however, built-in sequences all provide a :meth:`__getitem__`
785method that interprets negative indices by adding the length of the sequence
786to the index (so that ``x[-1]`` selects the last item of ``x``). The
787resulting value must be a nonnegative integer less than the number of items in
788the sequence, and the subscription selects the item whose index is that value
789(counting from zero). Since the support for negative indices and slicing
790occurs in the object's :meth:`__getitem__` method, subclasses overriding
791this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000792
793.. index::
794 single: character
795 pair: string; item
796
797A string's items are characters. A character is not a separate data type but a
798string of exactly one character.
799
800
801.. _slicings:
802
803Slicings
804--------
805
806.. index::
807 single: slicing
808 single: slice
809
810.. index::
811 object: sequence
812 object: string
813 object: tuple
814 object: list
815
816A slicing selects a range of items in a sequence object (e.g., a string, tuple
817or list). Slicings may be used as expressions or as targets in assignment or
818:keyword:`del` statements. The syntax for a slicing:
819
820.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000821 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000822 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000823 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000824 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000825 lower_bound: `expression`
826 upper_bound: `expression`
827 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000828
829There is ambiguity in the formal syntax here: anything that looks like an
830expression list also looks like a slice list, so any subscription can be
831interpreted as a slicing. Rather than further complicating the syntax, this is
832disambiguated by defining that in this case the interpretation as a subscription
833takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000834slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000835
836.. index::
837 single: start (slice object attribute)
838 single: stop (slice object attribute)
839 single: step (slice object attribute)
840
Georg Brandla4c8c472014-10-31 10:38:49 +0100841The semantics for a slicing are as follows. The primary is indexed (using the
842same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000843normal subscription) with a key that is constructed from the slice list, as
844follows. If the slice list contains at least one comma, the key is a tuple
845containing the conversion of the slice items; otherwise, the conversion of the
846lone slice item is the key. The conversion of a slice item that is an
847expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300848object (see section :ref:`types`) whose :attr:`~slice.start`,
849:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
850expressions given as lower bound, upper bound and stride, respectively,
851substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000852
853
Chris Jerdonekb4309942012-12-25 14:54:44 -0800854.. index::
855 object: callable
856 single: call
857 single: argument; call semantics
858
Georg Brandl116aa622007-08-15 14:28:22 +0000859.. _calls:
860
861Calls
862-----
863
Chris Jerdonekb4309942012-12-25 14:54:44 -0800864A call calls a callable object (e.g., a :term:`function`) with a possibly empty
865series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000866
867.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000868 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Martin Panter0c0da482016-06-12 01:46:50 +0000869 argument_list: `positional_arguments` ["," `starred_and_keywords`]
870 : ["," `keywords_arguments`]
871 : | `starred_and_keywords` ["," `keywords_arguments`]
872 : | `keywords_arguments`
873 positional_arguments: ["*"] `expression` ("," ["*"] `expression`)*
874 starred_and_keywords: ("*" `expression` | `keyword_item`)
875 : ("," "*" `expression` | "," `keyword_item`)*
876 keywords_arguments: (`keyword_item` | "**" `expression`)
Martin Panter7106a512016-12-24 10:20:38 +0000877 : ("," `keyword_item` | "," "**" `expression`)*
Georg Brandl116aa622007-08-15 14:28:22 +0000878 keyword_item: `identifier` "=" `expression`
879
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700880An optional trailing comma may be present after the positional and keyword arguments
881but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000882
Chris Jerdonekb4309942012-12-25 14:54:44 -0800883.. index::
884 single: parameter; call semantics
885
Georg Brandl116aa622007-08-15 14:28:22 +0000886The primary must evaluate to a callable object (user-defined functions, built-in
887functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000888instances, and all objects having a :meth:`__call__` method are callable). All
889argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800890to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000891
892.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000893
894If keyword arguments are present, they are first converted to positional
895arguments, as follows. First, a list of unfilled slots is created for the
896formal parameters. If there are N positional arguments, they are placed in the
897first N slots. Next, for each keyword argument, the identifier is used to
898determine the corresponding slot (if the identifier is the same as the first
899formal parameter name, the first slot is used, and so on). If the slot is
900already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
901the argument is placed in the slot, filling it (even if the expression is
902``None``, it fills the slot). When all arguments have been processed, the slots
903that are still unfilled are filled with the corresponding default value from the
904function definition. (Default values are calculated, once, when the function is
905defined; thus, a mutable object such as a list or dictionary used as default
906value will be shared by all calls that don't specify an argument value for the
907corresponding slot; this should usually be avoided.) If there are any unfilled
908slots for which no default value is specified, a :exc:`TypeError` exception is
909raised. Otherwise, the list of filled slots is used as the argument list for
910the call.
911
Georg Brandl495f7b52009-10-27 15:28:25 +0000912.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000913
Georg Brandl495f7b52009-10-27 15:28:25 +0000914 An implementation may provide built-in functions whose positional parameters
915 do not have names, even if they are 'named' for the purpose of documentation,
916 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000917 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000918 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000919
Georg Brandl116aa622007-08-15 14:28:22 +0000920If there are more positional arguments than there are formal parameter slots, a
921:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
922``*identifier`` is present; in this case, that formal parameter receives a tuple
923containing the excess positional arguments (or an empty tuple if there were no
924excess positional arguments).
925
926If any keyword argument does not correspond to a formal parameter name, a
927:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
928``**identifier`` is present; in this case, that formal parameter receives a
929dictionary containing the excess keyword arguments (using the keywords as keys
930and the argument values as corresponding values), or a (new) empty dictionary if
931there were no excess keyword arguments.
932
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300933.. index::
934 single: *; in function calls
Martin Panter0c0da482016-06-12 01:46:50 +0000935 single: unpacking; in function calls
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300936
Georg Brandl116aa622007-08-15 14:28:22 +0000937If the syntax ``*expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +0000938evaluate to an :term:`iterable`. Elements from these iterables are
939treated as if they were additional positional arguments. For the call
940``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*,
941this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
942*y1*, ..., *yM*, *x3*, *x4*.
Georg Brandl116aa622007-08-15 14:28:22 +0000943
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000944A consequence of this is that although the ``*expression`` syntax may appear
Martin Panter0c0da482016-06-12 01:46:50 +0000945*after* explicit keyword arguments, it is processed *before* the
946keyword arguments (and any ``**expression`` arguments -- see below). So::
Georg Brandl116aa622007-08-15 14:28:22 +0000947
948 >>> def f(a, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300949 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000950 ...
951 >>> f(b=1, *(2,))
952 2 1
953 >>> f(a=1, *(2,))
954 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530955 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000956 TypeError: f() got multiple values for keyword argument 'a'
957 >>> f(1, *(2,))
958 1 2
959
960It is unusual for both keyword arguments and the ``*expression`` syntax to be
961used in the same call, so in practice this confusion does not arise.
962
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300963.. index::
964 single: **; in function calls
965
Georg Brandl116aa622007-08-15 14:28:22 +0000966If the syntax ``**expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +0000967evaluate to a :term:`mapping`, the contents of which are treated as
968additional keyword arguments. If a keyword is already present
969(as an explicit keyword argument, or from another unpacking),
970a :exc:`TypeError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000971
972Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
973used as positional argument slots or as keyword argument names.
974
Martin Panter0c0da482016-06-12 01:46:50 +0000975.. versionchanged:: 3.5
976 Function calls accept any number of ``*`` and ``**`` unpackings,
977 positional arguments may follow iterable unpackings (``*``),
978 and keyword arguments may follow dictionary unpackings (``**``).
979 Originally proposed by :pep:`448`.
980
Georg Brandl116aa622007-08-15 14:28:22 +0000981A call always returns some value, possibly ``None``, unless it raises an
982exception. How this value is computed depends on the type of the callable
983object.
984
985If it is---
986
987a user-defined function:
988 .. index::
989 pair: function; call
990 triple: user-defined; function; call
991 object: user-defined function
992 object: function
993
994 The code block for the function is executed, passing it the argument list. The
995 first thing the code block will do is bind the formal parameters to the
996 arguments; this is described in section :ref:`function`. When the code block
997 executes a :keyword:`return` statement, this specifies the return value of the
998 function call.
999
1000a built-in function or method:
1001 .. index::
1002 pair: function; call
1003 pair: built-in function; call
1004 pair: method; call
1005 pair: built-in method; call
1006 object: built-in method
1007 object: built-in function
1008 object: method
1009 object: function
1010
1011 The result is up to the interpreter; see :ref:`built-in-funcs` for the
1012 descriptions of built-in functions and methods.
1013
1014a class object:
1015 .. index::
1016 object: class
1017 pair: class object; call
1018
1019 A new instance of that class is returned.
1020
1021a class instance method:
1022 .. index::
1023 object: class instance
1024 object: instance
1025 pair: class instance; call
1026
1027 The corresponding user-defined function is called, with an argument list that is
1028 one longer than the argument list of the call: the instance becomes the first
1029 argument.
1030
1031a class instance:
1032 .. index::
1033 pair: instance; call
1034 single: __call__() (object method)
1035
1036 The class must define a :meth:`__call__` method; the effect is then the same as
1037 if that method was called.
1038
1039
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001040.. _await:
1041
1042Await expression
1043================
1044
1045Suspend the execution of :term:`coroutine` on an :term:`awaitable` object.
1046Can only be used inside a :term:`coroutine function`.
1047
1048.. productionlist::
Serhiy Storchakac7cc9852016-05-08 21:59:46 +03001049 await_expr: "await" `primary`
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001050
1051.. versionadded:: 3.5
1052
1053
Georg Brandl116aa622007-08-15 14:28:22 +00001054.. _power:
1055
1056The power operator
1057==================
1058
1059The power operator binds more tightly than unary operators on its left; it binds
1060less tightly than unary operators on its right. The syntax is:
1061
1062.. productionlist::
Serhiy Storchakac7cc9852016-05-08 21:59:46 +03001063 power: ( `await_expr` | `primary` ) ["**" `u_expr`]
Georg Brandl116aa622007-08-15 14:28:22 +00001064
1065Thus, in an unparenthesized sequence of power and unary operators, the operators
1066are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +00001067for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001068
1069The power operator has the same semantics as the built-in :func:`pow` function,
1070when called with two arguments: it yields its left argument raised to the power
1071of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +00001072type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +00001073
Georg Brandl96593ed2007-09-07 14:15:41 +00001074For int operands, the result has the same type as the operands unless the second
1075argument is negative; in that case, all arguments are converted to float and a
1076float result is delivered. For example, ``10**2`` returns ``100``, but
1077``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +00001078
1079Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +00001080Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001081number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001082
1083
1084.. _unary:
1085
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001086Unary arithmetic and bitwise operations
1087=======================================
Georg Brandl116aa622007-08-15 14:28:22 +00001088
1089.. index::
1090 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +00001091 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001092
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001093All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +00001094
1095.. productionlist::
1096 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
1097
1098.. index::
1099 single: negation
1100 single: minus
1101
1102The unary ``-`` (minus) operator yields the negation of its numeric argument.
1103
1104.. index:: single: plus
1105
1106The unary ``+`` (plus) operator yields its numeric argument unchanged.
1107
1108.. index:: single: inversion
1109
Christian Heimesfaf2f632008-01-06 16:59:19 +00001110
Georg Brandl95817b32008-05-11 14:30:18 +00001111The unary ``~`` (invert) operator yields the bitwise inversion of its integer
1112argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
1113applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00001114
1115.. index:: exception: TypeError
1116
1117In all three cases, if the argument does not have the proper type, a
1118:exc:`TypeError` exception is raised.
1119
1120
1121.. _binary:
1122
1123Binary arithmetic operations
1124============================
1125
1126.. index:: triple: binary; arithmetic; operation
1127
1128The binary arithmetic operations have the conventional priority levels. Note
1129that some of these operations also apply to certain non-numeric types. Apart
1130from the power operator, there are only two levels, one for multiplicative
1131operators and one for additive operators:
1132
1133.. productionlist::
Benjamin Petersond51374e2014-04-09 23:55:56 -04001134 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
1135 : `m_expr` "//" `u_expr`| `m_expr` "/" `u_expr` |
1136 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001137 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
1138
1139.. index:: single: multiplication
1140
1141The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +00001142arguments must either both be numbers, or one argument must be an integer and
1143the other must be a sequence. In the former case, the numbers are converted to a
1144common type and then multiplied together. In the latter case, sequence
1145repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001146
Benjamin Petersond51374e2014-04-09 23:55:56 -04001147.. index:: single: matrix multiplication
1148
1149The ``@`` (at) operator is intended to be used for matrix multiplication. No
1150builtin Python types implement this operator.
1151
1152.. versionadded:: 3.5
1153
Georg Brandl116aa622007-08-15 14:28:22 +00001154.. index::
1155 exception: ZeroDivisionError
1156 single: division
1157
1158The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
1159their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +02001160Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +00001161integer; the result is that of mathematical division with the 'floor' function
1162applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
1163exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001164
1165.. index:: single: modulo
1166
1167The ``%`` (modulo) operator yields the remainder from the division of the first
1168argument by the second. The numeric arguments are first converted to a common
1169type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
1170arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
1171(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
1172result with the same sign as its second operand (or zero); the absolute value of
1173the result is strictly smaller than the absolute value of the second operand
1174[#]_.
1175
Georg Brandl96593ed2007-09-07 14:15:41 +00001176The floor division and modulo operators are connected by the following
1177identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
1178connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
1179x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +00001180
1181In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +00001182also overloaded by string objects to perform old-style string formatting (also
1183known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +00001184Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +00001185
1186The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +00001187function are not defined for complex numbers. Instead, convert to a floating
1188point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +00001189
1190.. index:: single: addition
1191
Georg Brandl96593ed2007-09-07 14:15:41 +00001192The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001193must either both be numbers or both be sequences of the same type. In the
1194former case, the numbers are converted to a common type and then added together.
1195In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +00001196
1197.. index:: single: subtraction
1198
1199The ``-`` (subtraction) operator yields the difference of its arguments. The
1200numeric arguments are first converted to a common type.
1201
1202
1203.. _shifting:
1204
1205Shifting operations
1206===================
1207
1208.. index:: pair: shifting; operation
1209
1210The shifting operations have lower priority than the arithmetic operations:
1211
1212.. productionlist::
1213 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
1214
Georg Brandl96593ed2007-09-07 14:15:41 +00001215These operators accept integers as arguments. They shift the first argument to
1216the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001217
1218.. index:: exception: ValueError
1219
Georg Brandl0aaae262013-10-08 21:47:18 +02001220A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
1221shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001222
1223
1224.. _bitwise:
1225
Christian Heimesfaf2f632008-01-06 16:59:19 +00001226Binary bitwise operations
1227=========================
Georg Brandl116aa622007-08-15 14:28:22 +00001228
Christian Heimesfaf2f632008-01-06 16:59:19 +00001229.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001230
1231Each of the three bitwise operations has a different priority level:
1232
1233.. productionlist::
1234 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1235 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1236 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1237
Christian Heimesfaf2f632008-01-06 16:59:19 +00001238.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +00001239
Georg Brandl96593ed2007-09-07 14:15:41 +00001240The ``&`` operator yields the bitwise AND of its arguments, which must be
1241integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001242
1243.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001244 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001245 pair: exclusive; or
1246
1247The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001248must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001249
1250.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001251 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001252 pair: inclusive; or
1253
1254The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001255must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001256
1257
1258.. _comparisons:
1259
1260Comparisons
1261===========
1262
1263.. index:: single: comparison
1264
1265.. index:: pair: C; language
1266
1267Unlike C, all comparison operations in Python have the same priority, which is
1268lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1269C, expressions like ``a < b < c`` have the interpretation that is conventional
1270in mathematics:
1271
1272.. productionlist::
1273 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1274 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1275 : | "is" ["not"] | ["not"] "in"
1276
1277Comparisons yield boolean values: ``True`` or ``False``.
1278
1279.. index:: pair: chaining; comparisons
1280
1281Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1282``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1283cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1284
Guido van Rossum04110fb2007-08-24 16:32:05 +00001285Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1286*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1287to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1288evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001289
Guido van Rossum04110fb2007-08-24 16:32:05 +00001290Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001291*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1292pretty).
1293
Martin Panteraa0da862015-09-23 05:28:13 +00001294Value comparisons
1295-----------------
1296
Georg Brandl116aa622007-08-15 14:28:22 +00001297The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
Martin Panteraa0da862015-09-23 05:28:13 +00001298values of two objects. The objects do not need to have the same type.
Georg Brandl116aa622007-08-15 14:28:22 +00001299
Martin Panteraa0da862015-09-23 05:28:13 +00001300Chapter :ref:`objects` states that objects have a value (in addition to type
1301and identity). The value of an object is a rather abstract notion in Python:
1302For example, there is no canonical access method for an object's value. Also,
1303there is no requirement that the value of an object should be constructed in a
1304particular way, e.g. comprised of all its data attributes. Comparison operators
1305implement a particular notion of what the value of an object is. One can think
1306of them as defining the value of an object indirectly, by means of their
1307comparison implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00001308
Martin Panteraa0da862015-09-23 05:28:13 +00001309Because all types are (direct or indirect) subtypes of :class:`object`, they
1310inherit the default comparison behavior from :class:`object`. Types can
1311customize their comparison behavior by implementing
1312:dfn:`rich comparison methods` like :meth:`__lt__`, described in
1313:ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001314
Martin Panteraa0da862015-09-23 05:28:13 +00001315The default behavior for equality comparison (``==`` and ``!=``) is based on
1316the identity of the objects. Hence, equality comparison of instances with the
1317same identity results in equality, and equality comparison of instances with
1318different identities results in inequality. A motivation for this default
1319behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1320implies ``x == y``).
1321
1322A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1323an attempt raises :exc:`TypeError`. A motivation for this default behavior is
1324the lack of a similar invariant as for equality.
1325
1326The behavior of the default equality comparison, that instances with different
1327identities are always unequal, may be in contrast to what types will need that
1328have a sensible definition of object value and value-based equality. Such
1329types will need to customize their comparison behavior, and in fact, a number
1330of built-in types have done that.
1331
1332The following list describes the comparison behavior of the most important
1333built-in types.
1334
1335* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1336 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
1337 compared within and across their types, with the restriction that complex
1338 numbers do not support order comparison. Within the limits of the types
1339 involved, they compare mathematically (algorithmically) correct without loss
1340 of precision.
1341
1342 The not-a-number values :const:`float('NaN')` and :const:`Decimal('NaN')`
1343 are special. They are identical to themselves (``x is x`` is true) but
1344 are not equal to themselves (``x == x`` is false). Additionally,
1345 comparing any number to a not-a-number value
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001346 will return ``False``. For example, both ``3 < float('NaN')`` and
1347 ``float('NaN') < 3`` will return ``False``.
1348
Martin Panteraa0da862015-09-23 05:28:13 +00001349* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
1350 compared within and across their types. They compare lexicographically using
1351 the numeric values of their elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001352
Martin Panteraa0da862015-09-23 05:28:13 +00001353* Strings (instances of :class:`str`) compare lexicographically using the
1354 numerical Unicode code points (the result of the built-in function
1355 :func:`ord`) of their characters. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001356
Martin Panteraa0da862015-09-23 05:28:13 +00001357 Strings and binary sequences cannot be directly compared.
Georg Brandl116aa622007-08-15 14:28:22 +00001358
Martin Panteraa0da862015-09-23 05:28:13 +00001359* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can
1360 be compared only within each of their types, with the restriction that ranges
1361 do not support order comparison. Equality comparison across these types
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +02001362 results in inequality, and ordering comparison across these types raises
Martin Panteraa0da862015-09-23 05:28:13 +00001363 :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001364
Martin Panteraa0da862015-09-23 05:28:13 +00001365 Sequences compare lexicographically using comparison of corresponding
1366 elements, whereby reflexivity of the elements is enforced.
Georg Brandl116aa622007-08-15 14:28:22 +00001367
Martin Panteraa0da862015-09-23 05:28:13 +00001368 In enforcing reflexivity of elements, the comparison of collections assumes
1369 that for a collection element ``x``, ``x == x`` is always true. Based on
1370 that assumption, element identity is compared first, and element comparison
1371 is performed only for distinct elements. This approach yields the same
1372 result as a strict element comparison would, if the compared elements are
1373 reflexive. For non-reflexive elements, the result is different than for
1374 strict element comparison, and may be surprising: The non-reflexive
1375 not-a-number values for example result in the following comparison behavior
1376 when used in a list::
1377
1378 >>> nan = float('NaN')
1379 >>> nan is nan
1380 True
1381 >>> nan == nan
1382 False <-- the defined non-reflexive behavior of NaN
1383 >>> [nan] == [nan]
1384 True <-- list enforces reflexivity and tests identity first
1385
1386 Lexicographical comparison between built-in collections works as follows:
1387
1388 - For two collections to compare equal, they must be of the same type, have
1389 the same length, and each pair of corresponding elements must compare
1390 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1391 same).
1392
1393 - Collections that support order comparison are ordered the same as their
1394 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same
1395 value as ``x <= y``). If a corresponding element does not exist, the
1396 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1397 true).
1398
1399* Mappings (instances of :class:`dict`) compare equal if and only if they have
cocoatomocdcac032017-03-31 14:48:49 +09001400 equal `(key, value)` pairs. Equality comparison of the keys and values
Martin Panteraa0da862015-09-23 05:28:13 +00001401 enforces reflexivity.
1402
1403 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
1404
1405* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within
1406 and across their types.
1407
1408 They define order
1409 comparison operators to mean subset and superset tests. Those relations do
1410 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}``
1411 are not equal, nor subsets of one another, nor supersets of one
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001412 another). Accordingly, sets are not appropriate arguments for functions
Martin Panteraa0da862015-09-23 05:28:13 +00001413 which depend on total ordering (for example, :func:`min`, :func:`max`, and
1414 :func:`sorted` produce undefined results given a list of sets as inputs).
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001415
Martin Panteraa0da862015-09-23 05:28:13 +00001416 Comparison of sets enforces reflexivity of its elements.
Georg Brandl116aa622007-08-15 14:28:22 +00001417
Martin Panteraa0da862015-09-23 05:28:13 +00001418* Most other built-in types have no comparison methods implemented, so they
1419 inherit the default comparison behavior.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001420
Martin Panteraa0da862015-09-23 05:28:13 +00001421User-defined classes that customize their comparison behavior should follow
1422some consistency rules, if possible:
1423
1424* Equality comparison should be reflexive.
1425 In other words, identical objects should compare equal:
1426
1427 ``x is y`` implies ``x == y``
1428
1429* Comparison should be symmetric.
1430 In other words, the following expressions should have the same result:
1431
1432 ``x == y`` and ``y == x``
1433
1434 ``x != y`` and ``y != x``
1435
1436 ``x < y`` and ``y > x``
1437
1438 ``x <= y`` and ``y >= x``
1439
1440* Comparison should be transitive.
1441 The following (non-exhaustive) examples illustrate that:
1442
1443 ``x > y and y > z`` implies ``x > z``
1444
1445 ``x < y and y <= z`` implies ``x < z``
1446
1447* Inverse comparison should result in the boolean negation.
1448 In other words, the following expressions should have the same result:
1449
1450 ``x == y`` and ``not x != y``
1451
1452 ``x < y`` and ``not x >= y`` (for total ordering)
1453
1454 ``x > y`` and ``not x <= y`` (for total ordering)
1455
1456 The last two expressions apply to totally ordered collections (e.g. to
1457 sequences, but not to sets or mappings). See also the
1458 :func:`~functools.total_ordering` decorator.
1459
Martin Panter8dbb0ca2017-01-29 10:00:23 +00001460* The :func:`hash` result should be consistent with equality.
1461 Objects that are equal should either have the same hash value,
1462 or be marked as unhashable.
1463
Martin Panteraa0da862015-09-23 05:28:13 +00001464Python does not enforce these consistency rules. In fact, the not-a-number
1465values are an example for not following these rules.
1466
1467
1468.. _in:
1469.. _not in:
Georg Brandl495f7b52009-10-27 15:28:25 +00001470.. _membership-test-details:
1471
Martin Panteraa0da862015-09-23 05:28:13 +00001472Membership test operations
1473--------------------------
1474
Georg Brandl96593ed2007-09-07 14:15:41 +00001475The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301476s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
1477``x not in s`` returns the negation of ``x in s``. All built-in sequences and
1478set types support this as well as dictionary, for which :keyword:`in` tests
1479whether the dictionary has a given key. For container types such as list, tuple,
1480set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001481to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001482
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301483For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
Georg Brandl4b491312007-08-31 09:22:56 +00001484substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1485always considered to be a substring of any other string, so ``"" in "abc"`` will
1486return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001487
Georg Brandl116aa622007-08-15 14:28:22 +00001488For user-defined classes which define the :meth:`__contains__` method, ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301489y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and
1490``False`` otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001491
Georg Brandl495f7b52009-10-27 15:28:25 +00001492For user-defined classes which do not define :meth:`__contains__` but do define
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301493:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z`` with ``x == z`` is
Georg Brandl495f7b52009-10-27 15:28:25 +00001494produced while iterating over ``y``. If an exception is raised during the
1495iteration, it is as if :keyword:`in` raised that exception.
1496
1497Lastly, the old-style iteration protocol is tried: if a class defines
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301498:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
Georg Brandl116aa622007-08-15 14:28:22 +00001499integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001500raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001501if :keyword:`in` raised that exception).
1502
1503.. index::
1504 operator: in
1505 operator: not in
1506 pair: membership; test
1507 object: sequence
1508
1509The operator :keyword:`not in` is defined to have the inverse true value of
1510:keyword:`in`.
1511
1512.. index::
1513 operator: is
1514 operator: is not
1515 pair: identity; test
1516
Martin Panteraa0da862015-09-23 05:28:13 +00001517
1518.. _is:
1519.. _is not:
1520
1521Identity comparisons
1522--------------------
1523
Georg Brandl116aa622007-08-15 14:28:22 +00001524The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
Raymond Hettinger06e18a72016-09-11 17:23:49 -07001525is y`` is true if and only if *x* and *y* are the same object. Object identity
1526is determined using the :meth:`id` function. ``x is not y`` yields the inverse
1527truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001528
1529
1530.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001531.. _and:
1532.. _or:
1533.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001534
1535Boolean operations
1536==================
1537
1538.. index::
1539 pair: Conditional; expression
1540 pair: Boolean; operation
1541
Georg Brandl116aa622007-08-15 14:28:22 +00001542.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001543 or_test: `and_test` | `or_test` "or" `and_test`
1544 and_test: `not_test` | `and_test` "and" `not_test`
1545 not_test: `comparison` | "not" `not_test`
1546
1547In the context of Boolean operations, and also when expressions are used by
1548control flow statements, the following values are interpreted as false:
1549``False``, ``None``, numeric zero of all types, and empty strings and containers
1550(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001551other values are interpreted as true. User-defined objects can customize their
1552truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001553
1554.. index:: operator: not
1555
1556The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1557otherwise.
1558
Georg Brandl116aa622007-08-15 14:28:22 +00001559.. index:: operator: and
1560
1561The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1562returned; otherwise, *y* is evaluated and the resulting value is returned.
1563
1564.. index:: operator: or
1565
1566The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1567returned; otherwise, *y* is evaluated and the resulting value is returned.
1568
1569(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1570they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001571argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001572replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001573the desired value. Because :keyword:`not` has to create a new value, it
1574returns a boolean value regardless of the type of its argument
1575(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001576
1577
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001578Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001579=======================
1580
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001581.. index::
1582 pair: conditional; expression
1583 pair: ternary; operator
1584
1585.. productionlist::
1586 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001587 expression: `conditional_expression` | `lambda_expr`
1588 expression_nocond: `or_test` | `lambda_expr_nocond`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001589
1590Conditional expressions (sometimes called a "ternary operator") have the lowest
1591priority of all Python operations.
1592
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001593The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1594If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001595evaluated and its value is returned.
1596
1597See :pep:`308` for more details about conditional expressions.
1598
1599
Georg Brandl116aa622007-08-15 14:28:22 +00001600.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001601.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001602
1603Lambdas
1604=======
1605
1606.. index::
1607 pair: lambda; expression
1608 pair: lambda; form
1609 pair: anonymous; function
1610
1611.. productionlist::
Georg Brandl242e6a02013-10-06 10:28:39 +02001612 lambda_expr: "lambda" [`parameter_list`]: `expression`
1613 lambda_expr_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001614
Zachary Ware2f78b842014-06-03 09:32:40 -05001615Lambda expressions (sometimes called lambda forms) are used to create anonymous
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001616functions. The expression ``lambda arguments: expression`` yields a function
Martin Panter1050d2d2016-07-26 11:18:21 +02001617object. The unnamed object behaves like a function object defined with:
1618
1619.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +00001620
Georg Brandl96593ed2007-09-07 14:15:41 +00001621 def <lambda>(arguments):
Georg Brandl116aa622007-08-15 14:28:22 +00001622 return expression
1623
1624See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001625functions created with lambda expressions cannot contain statements or
1626annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001627
Georg Brandl116aa622007-08-15 14:28:22 +00001628
1629.. _exprlists:
1630
1631Expression lists
1632================
1633
1634.. index:: pair: expression; list
1635
1636.. productionlist::
1637 expression_list: `expression` ( "," `expression` )* [","]
Martin Panter0c0da482016-06-12 01:46:50 +00001638 starred_list: `starred_item` ( "," `starred_item` )* [","]
1639 starred_expression: `expression` | ( `starred_item` "," )* [`starred_item`]
1640 starred_item: `expression` | "*" `or_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001641
1642.. index:: object: tuple
1643
Martin Panter0c0da482016-06-12 01:46:50 +00001644Except when part of a list or set display, an expression list
1645containing at least one comma yields a tuple. The length of
Georg Brandl116aa622007-08-15 14:28:22 +00001646the tuple is the number of expressions in the list. The expressions are
1647evaluated from left to right.
1648
Martin Panter0c0da482016-06-12 01:46:50 +00001649.. index::
1650 pair: iterable; unpacking
1651 single: *; in expression lists
1652
1653An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be
1654an :term:`iterable`. The iterable is expanded into a sequence of items,
1655which are included in the new tuple, list, or set, at the site of
1656the unpacking.
1657
1658.. versionadded:: 3.5
1659 Iterable unpacking in expression lists, originally proposed by :pep:`448`.
1660
Georg Brandl116aa622007-08-15 14:28:22 +00001661.. index:: pair: trailing; comma
1662
1663The trailing comma is required only to create a single tuple (a.k.a. a
1664*singleton*); it is optional in all other cases. A single expression without a
1665trailing comma doesn't create a tuple, but rather yields the value of that
1666expression. (To create an empty tuple, use an empty pair of parentheses:
1667``()``.)
1668
1669
1670.. _evalorder:
1671
1672Evaluation order
1673================
1674
1675.. index:: pair: evaluation; order
1676
Georg Brandl96593ed2007-09-07 14:15:41 +00001677Python evaluates expressions from left to right. Notice that while evaluating
1678an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001679
1680In the following lines, expressions will be evaluated in the arithmetic order of
1681their suffixes::
1682
1683 expr1, expr2, expr3, expr4
1684 (expr1, expr2, expr3, expr4)
1685 {expr1: expr2, expr3: expr4}
1686 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001687 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001688 expr3, expr4 = expr1, expr2
1689
1690
1691.. _operator-summary:
1692
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001693Operator precedence
1694===================
Georg Brandl116aa622007-08-15 14:28:22 +00001695
1696.. index:: pair: operator; precedence
1697
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001698The following table summarizes the operator precedence in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001699precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001700the same box have the same precedence. Unless the syntax is explicitly given,
1701operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001702exponentiation, which groups from right to left).
1703
1704Note that comparisons, membership tests, and identity tests, all have the same
1705precedence and have a left-to-right chaining feature as described in the
1706:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001707
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001708
1709+-----------------------------------------------+-------------------------------------+
1710| Operator | Description |
1711+===============================================+=====================================+
1712| :keyword:`lambda` | Lambda expression |
1713+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001714| :keyword:`if` -- :keyword:`else` | Conditional expression |
1715+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001716| :keyword:`or` | Boolean OR |
1717+-----------------------------------------------+-------------------------------------+
1718| :keyword:`and` | Boolean AND |
1719+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001720| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001721+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001722| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001723| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001724| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001725+-----------------------------------------------+-------------------------------------+
1726| ``|`` | Bitwise OR |
1727+-----------------------------------------------+-------------------------------------+
1728| ``^`` | Bitwise XOR |
1729+-----------------------------------------------+-------------------------------------+
1730| ``&`` | Bitwise AND |
1731+-----------------------------------------------+-------------------------------------+
1732| ``<<``, ``>>`` | Shifts |
1733+-----------------------------------------------+-------------------------------------+
1734| ``+``, ``-`` | Addition and subtraction |
1735+-----------------------------------------------+-------------------------------------+
Benjamin Petersond51374e2014-04-09 23:55:56 -04001736| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
svelankar9b47af62017-09-17 20:56:16 -04001737| | multiplication, division, floor |
1738| | division, remainder [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001739+-----------------------------------------------+-------------------------------------+
1740| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1741+-----------------------------------------------+-------------------------------------+
1742| ``**`` | Exponentiation [#]_ |
1743+-----------------------------------------------+-------------------------------------+
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001744| ``await`` ``x`` | Await expression |
1745+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001746| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1747| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1748+-----------------------------------------------+-------------------------------------+
1749| ``(expressions...)``, | Binding or tuple display, |
1750| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001751| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001752| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001753+-----------------------------------------------+-------------------------------------+
1754
Georg Brandl116aa622007-08-15 14:28:22 +00001755
1756.. rubric:: Footnotes
1757
Georg Brandl116aa622007-08-15 14:28:22 +00001758.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1759 true numerically due to roundoff. For example, and assuming a platform on which
1760 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1761 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001762 1e100``, which is numerically exactly equal to ``1e100``. The function
1763 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001764 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1765 is more appropriate depends on the application.
1766
1767.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001768 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001769 cases, Python returns the latter result, in order to preserve that
1770 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1771
Martin Panteraa0da862015-09-23 05:28:13 +00001772.. [#] The Unicode standard distinguishes between :dfn:`code points`
1773 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
1774 While most abstract characters in Unicode are only represented using one
1775 code point, there is a number of abstract characters that can in addition be
1776 represented using a sequence of more than one code point. For example, the
1777 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
1778 as a single :dfn:`precomposed character` at code position U+00C7, or as a
1779 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
1780 LETTER C), followed by a :dfn:`combining character` at code position U+0327
1781 (COMBINING CEDILLA).
1782
1783 The comparison operators on strings compare at the level of Unicode code
1784 points. This may be counter-intuitive to humans. For example,
1785 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1786 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".
1787
1788 To compare strings at the level of abstract characters (that is, in a way
1789 intuitive to humans), use :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001790
Georg Brandl48310cd2009-01-03 21:18:54 +00001791.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001792 descriptors, you may notice seemingly unusual behaviour in certain uses of
1793 the :keyword:`is` operator, like those involving comparisons between instance
1794 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001795
Georg Brandl063f2372010-12-01 15:32:43 +00001796.. [#] The ``%`` operator is also used for string formatting; the same
1797 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001798
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001799.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1800 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.