blob: d210769225d43345e5dcceb897de7a2e725c999b [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
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300131.. index::
132 single: parenthesized form
133 single: (; tuple display
134 single: ); tuple display
Georg Brandl116aa622007-08-15 14:28:22 +0000135
136A parenthesized form is an optional expression list enclosed in parentheses:
137
138.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000139 parenth_form: "(" [`starred_expression`] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141A parenthesized expression list yields whatever that expression list yields: if
142the list contains at least one comma, it yields a tuple; otherwise, it yields
143the single expression that makes up the expression list.
144
145.. index:: pair: empty; tuple
146
147An empty pair of parentheses yields an empty tuple object. Since tuples are
148immutable, the rules for literals apply (i.e., two occurrences of the empty
149tuple may or may not yield the same object).
150
151.. index::
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300152 single: comma; tuple display
Georg Brandl116aa622007-08-15 14:28:22 +0000153 pair: tuple; display
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300154 single: ,; tuple display
Georg Brandl116aa622007-08-15 14:28:22 +0000155
156Note that tuples are not formed by the parentheses, but rather by use of the
157comma operator. The exception is the empty tuple, for which parentheses *are*
158required --- allowing unparenthesized "nothing" in expressions would cause
159ambiguities and allow common typos to pass uncaught.
160
161
Georg Brandl96593ed2007-09-07 14:15:41 +0000162.. _comprehensions:
163
164Displays for lists, sets and dictionaries
165-----------------------------------------
166
167For constructing a list, a set or a dictionary Python provides special syntax
168called "displays", each of them in two flavors:
169
170* either the container contents are listed explicitly, or
171
172* they are computed via a set of looping and filtering instructions, called a
173 :dfn:`comprehension`.
174
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300175.. index::
176 single: for; in comprehensions
177 single: if; in comprehensions
178 single: async for; in comprehensions
179
Georg Brandl96593ed2007-09-07 14:15:41 +0000180Common syntax elements for comprehensions are:
181
182.. productionlist::
183 comprehension: `expression` `comp_for`
Miss Islington (bot)4dc3c8f2018-04-11 10:07:23 -0700184 comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`]
Georg Brandl96593ed2007-09-07 14:15:41 +0000185 comp_iter: `comp_for` | `comp_if`
186 comp_if: "if" `expression_nocond` [`comp_iter`]
187
188The comprehension consists of a single expression followed by at least one
189:keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` clauses.
190In this case, the elements of the new container are those that would be produced
191by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
192nesting from left to right, and evaluating the expression to produce an element
193each time the innermost block is reached.
194
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200195However, aside from the iterable expression in the leftmost :keyword:`for` clause,
196the comprehension is executed in a separate implicitly nested scope. This ensures
197that names assigned to in the target list don't "leak" into the enclosing scope.
198
199The iterable expression in the leftmost :keyword:`for` clause is evaluated
200directly in the enclosing scope and then passed as an argument to the implictly
201nested scope. Subsequent :keyword:`for` clauses and any filter condition in the
202leftmost :keyword:`for` clause cannot be evaluated in the enclosing scope as
203they may depend on the values obtained from the leftmost iterable. For example:
204``[x*y for x in range(10) for y in range(x, x+10)]``.
205
206To ensure the comprehension always results in a container of the appropriate
207type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly
208nested scope (in Python 3.7, such expressions emit :exc:`DeprecationWarning`
209when compiled, in Python 3.8+ they will emit :exc:`SyntaxError`).
Georg Brandl02c30562007-09-07 17:52:53 +0000210
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300211.. index::
212 single: await; in comprehensions
213
Yury Selivanov03660042016-12-15 17:36:05 -0500214Since Python 3.6, in an :keyword:`async def` function, an :keyword:`async for`
215clause may be used to iterate over a :term:`asynchronous iterator`.
216A comprehension in an :keyword:`async def` function may consist of either a
217:keyword:`for` or :keyword:`async for` clause following the leading
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +0200218expression, may contain additional :keyword:`for` or :keyword:`async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500219clauses, and may also use :keyword:`await` expressions.
220If a comprehension contains either :keyword:`async for` clauses
221or :keyword:`await` expressions it is called an
222:dfn:`asynchronous comprehension`. An asynchronous comprehension may
223suspend the execution of the coroutine function in which it appears.
224See also :pep:`530`.
Georg Brandl96593ed2007-09-07 14:15:41 +0000225
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200226.. versionadded:: 3.6
227 Asynchronous comprehensions were introduced.
228
229.. deprecated:: 3.7
230 ``yield`` and ``yield from`` deprecated in the implicitly nested scope.
231
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233.. _lists:
234
235List displays
236-------------
237
238.. index::
239 pair: list; display
240 pair: list; comprehensions
Georg Brandl96593ed2007-09-07 14:15:41 +0000241 pair: empty; list
242 object: list
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300243 single: [; list expression
244 single: ]; list expression
245 single: ,; expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247A list display is a possibly empty series of expressions enclosed in square
248brackets:
249
250.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000251 list_display: "[" [`starred_list` | `comprehension`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000252
Georg Brandl96593ed2007-09-07 14:15:41 +0000253A list display yields a new list object, the contents being specified by either
254a list of expressions or a comprehension. When a comma-separated list of
255expressions is supplied, its elements are evaluated from left to right and
256placed into the list object in that order. When a comprehension is supplied,
257the list is constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000258
259
Georg Brandl96593ed2007-09-07 14:15:41 +0000260.. _set:
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Georg Brandl96593ed2007-09-07 14:15:41 +0000262Set displays
263------------
Georg Brandl116aa622007-08-15 14:28:22 +0000264
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300265.. index::
266 pair: set; display
267 object: set
268 single: {; set expression
269 single: }; set expression
270 single: ,; expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000271
Georg Brandl96593ed2007-09-07 14:15:41 +0000272A set display is denoted by curly braces and distinguishable from dictionary
273displays by the lack of colons separating keys and values:
Georg Brandl116aa622007-08-15 14:28:22 +0000274
275.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000276 set_display: "{" (`starred_list` | `comprehension`) "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000277
Georg Brandl96593ed2007-09-07 14:15:41 +0000278A set display yields a new mutable set object, the contents being specified by
279either a sequence of expressions or a comprehension. When a comma-separated
280list of expressions is supplied, its elements are evaluated from left to right
281and added to the set object. When a comprehension is supplied, the set is
282constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Georg Brandl528cdb12008-09-21 07:09:51 +0000284An empty set cannot be constructed with ``{}``; this literal constructs an empty
285dictionary.
Christian Heimes78644762008-03-04 23:39:23 +0000286
287
Georg Brandl116aa622007-08-15 14:28:22 +0000288.. _dict:
289
290Dictionary displays
291-------------------
292
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300293.. index::
294 pair: dictionary; display
295 key, datum, key/datum pair
296 object: dictionary
297 single: {; dictionary expression
298 single: }; dictionary expression
299 single: :; in dictionary expressions
300 single: ,; in dictionary displays
Georg Brandl116aa622007-08-15 14:28:22 +0000301
302A dictionary display is a possibly empty series of key/datum pairs enclosed in
303curly braces:
304
305.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000306 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000307 key_datum_list: `key_datum` ("," `key_datum`)* [","]
Martin Panter0c0da482016-06-12 01:46:50 +0000308 key_datum: `expression` ":" `expression` | "**" `or_expr`
Georg Brandl96593ed2007-09-07 14:15:41 +0000309 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311A dictionary display yields a new dictionary object.
312
Georg Brandl96593ed2007-09-07 14:15:41 +0000313If a comma-separated sequence of key/datum pairs is given, they are evaluated
314from left to right to define the entries of the dictionary: each key object is
315used as a key into the dictionary to store the corresponding datum. This means
316that you can specify the same key multiple times in the key/datum list, and the
317final dictionary's value for that key will be the last one given.
318
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300319.. index::
320 unpacking; dictionary
321 single: **; in dictionary displays
Martin Panter0c0da482016-06-12 01:46:50 +0000322
323A double asterisk ``**`` denotes :dfn:`dictionary unpacking`.
324Its operand must be a :term:`mapping`. Each mapping item is added
325to the new dictionary. Later values replace values already set by
326earlier key/datum pairs and earlier dictionary unpackings.
327
328.. versionadded:: 3.5
329 Unpacking into dictionary displays, originally proposed by :pep:`448`.
330
Georg Brandl96593ed2007-09-07 14:15:41 +0000331A dict comprehension, in contrast to list and set comprehensions, needs two
332expressions separated with a colon followed by the usual "for" and "if" clauses.
333When the comprehension is run, the resulting key and value elements are inserted
334in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000337 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000338
339Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000340:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000341all mutable objects.) Clashes between duplicate keys are not detected; the last
342datum (textually rightmost in the display) stored for a given key value
343prevails.
344
345
Georg Brandl96593ed2007-09-07 14:15:41 +0000346.. _genexpr:
347
348Generator expressions
349---------------------
350
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300351.. index::
352 pair: generator; expression
353 object: generator
354 single: (; generator expression
355 single: ); generator expression
Georg Brandl96593ed2007-09-07 14:15:41 +0000356
357A generator expression is a compact generator notation in parentheses:
358
359.. productionlist::
360 generator_expression: "(" `expression` `comp_for` ")"
361
362A generator expression yields a new generator object. Its syntax is the same as
363for comprehensions, except that it is enclosed in parentheses instead of
364brackets or curly braces.
365
366Variables used in the generator expression are evaluated lazily when the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700367:meth:`~generator.__next__` method is called for the generator object (in the same
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200368fashion as normal generators). However, the iterable expression in the
369leftmost :keyword:`for` clause is immediately evaluated, so that an error
370produced by it will be emitted at the point where the generator expression
371is defined, rather than at the point where the first value is retrieved.
372Subsequent :keyword:`for` clauses and any filter condition in the leftmost
373:keyword:`for` clause cannot be evaluated in the enclosing scope as they may
374depend on the values obtained from the leftmost iterable. For example:
375``(x*y for x in range(10) for y in range(x, x+10))``.
Georg Brandl96593ed2007-09-07 14:15:41 +0000376
377The parentheses can be omitted on calls with only one argument. See section
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700378:ref:`calls` for details.
Georg Brandl96593ed2007-09-07 14:15:41 +0000379
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200380To avoid interfering with the expected operation of the generator expression
381itself, ``yield`` and ``yield from`` expressions are prohibited in the
382implicitly defined generator (in Python 3.7, such expressions emit
383:exc:`DeprecationWarning` when compiled, in Python 3.8+ they will emit
384:exc:`SyntaxError`).
385
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400386If a generator expression contains either :keyword:`async for`
387clauses or :keyword:`await` expressions it is called an
388:dfn:`asynchronous generator expression`. An asynchronous generator
389expression returns a new asynchronous generator object,
390which is an asynchronous iterator (see :ref:`async-iterators`).
391
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200392.. versionadded:: 3.6
393 Asynchronous generator expressions were introduced.
394
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400395.. versionchanged:: 3.7
396 Prior to Python 3.7, asynchronous generator expressions could
397 only appear in :keyword:`async def` coroutines. Starting
398 with 3.7, any function can use asynchronous generator expressions.
Georg Brandl96593ed2007-09-07 14:15:41 +0000399
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200400.. deprecated:: 3.7
401 ``yield`` and ``yield from`` deprecated in the implicitly nested scope.
402
403
Georg Brandl116aa622007-08-15 14:28:22 +0000404.. _yieldexpr:
405
406Yield expressions
407-----------------
408
409.. index::
410 keyword: yield
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300411 keyword: from
Georg Brandl116aa622007-08-15 14:28:22 +0000412 pair: yield; expression
413 pair: generator; function
414
415.. productionlist::
416 yield_atom: "(" `yield_expression` ")"
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000417 yield_expression: "yield" [`expression_list` | "from" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000418
Yury Selivanov03660042016-12-15 17:36:05 -0500419The yield expression is used when defining a :term:`generator` function
420or an :term:`asynchronous generator` function and
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500421thus can only be used in the body of a function definition. Using a yield
Yury Selivanov03660042016-12-15 17:36:05 -0500422expression in a function's body causes that function to be a generator,
423and using it in an :keyword:`async def` function's body causes that
424coroutine function to be an asynchronous generator. For example::
425
426 def gen(): # defines a generator function
427 yield 123
428
429 async def agen(): # defines an asynchronous generator function (PEP 525)
430 yield 123
431
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200432Due to their side effects on the containing scope, ``yield`` expressions
433are not permitted as part of the implicitly defined scopes used to
434implement comprehensions and generator expressions (in Python 3.7, such
435expressions emit :exc:`DeprecationWarning` when compiled, in Python 3.8+
436they will emit :exc:`SyntaxError`)..
437
438.. deprecated:: 3.7
439 Yield expressions deprecated in the implicitly nested scopes used to
440 implement comprehensions and generator expressions.
441
Yury Selivanov03660042016-12-15 17:36:05 -0500442Generator functions are described below, while asynchronous generator
443functions are described separately in section
444:ref:`asynchronous-generator-functions`.
Georg Brandl116aa622007-08-15 14:28:22 +0000445
446When a generator function is called, it returns an iterator known as a
Guido van Rossumd0150ad2015-05-05 12:02:01 -0700447generator. That generator then controls the execution of the generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000448The execution starts when one of the generator's methods is called. At that
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500449time, the execution proceeds to the first yield expression, where it is
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700450suspended again, returning the value of :token:`expression_list` to the generator's
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500451caller. By suspended, we mean that all local state is retained, including the
Ethan Furman2f825af2015-01-14 22:25:27 -0800452current bindings of local variables, the instruction pointer, the internal
453evaluation stack, and the state of any exception handling. When the execution
454is resumed by calling one of the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500455generator's methods, the function can proceed exactly as if the yield expression
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700456were just another external call. The value of the yield expression after
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500457resuming depends on the method which resumed the execution. If
458:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or
459the :func:`next` builtin) then the result is :const:`None`. Otherwise, if
460:meth:`~generator.send` is used, then the result will be the value passed in to
461that method.
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463.. index:: single: coroutine
464
465All of this makes generator functions quite similar to coroutines; they yield
466multiple times, they have more than one entry point and their execution can be
467suspended. The only difference is that a generator function cannot control
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700468where the execution should continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000469transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000470
Ethan Furman2f825af2015-01-14 22:25:27 -0800471Yield expressions are allowed anywhere in a :keyword:`try` construct. If the
472generator is not resumed before it is
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500473finalized (by reaching a zero reference count or by being garbage collected),
474the generator-iterator's :meth:`~generator.close` method will be called,
475allowing any pending :keyword:`finally` clauses to execute.
Georg Brandl02c30562007-09-07 17:52:53 +0000476
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300477.. index::
478 single: from; yield from expression
479
Nick Coghlan0ed80192012-01-14 14:43:24 +1000480When ``yield from <expr>`` is used, it treats the supplied expression as
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000481a subiterator. All values produced by that subiterator are passed directly
482to the caller of the current generator's methods. Any values passed in with
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300483:meth:`~generator.send` and any exceptions passed in with
484:meth:`~generator.throw` are passed to the underlying iterator if it has the
485appropriate methods. If this is not the case, then :meth:`~generator.send`
486will raise :exc:`AttributeError` or :exc:`TypeError`, while
487:meth:`~generator.throw` will just raise the passed in exception immediately.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000488
489When the underlying iterator is complete, the :attr:`~StopIteration.value`
490attribute of the raised :exc:`StopIteration` instance becomes the value of
491the yield expression. It can be either set explicitly when raising
492:exc:`StopIteration`, or automatically when the sub-iterator is a generator
493(by returning a value from the sub-generator).
494
Nick Coghlan0ed80192012-01-14 14:43:24 +1000495 .. versionchanged:: 3.3
Martin Panterd21e0b52015-10-10 10:36:22 +0000496 Added ``yield from <expr>`` to delegate control flow to a subiterator.
Nick Coghlan0ed80192012-01-14 14:43:24 +1000497
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500498The parentheses may be omitted when the yield expression is the sole expression
499on the right hand side of an assignment statement.
500
501.. seealso::
502
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300503 :pep:`255` - Simple Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500504 The proposal for adding generators and the :keyword:`yield` statement to Python.
505
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300506 :pep:`342` - Coroutines via Enhanced Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500507 The proposal to enhance the API and syntax of generators, making them
508 usable as simple coroutines.
509
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300510 :pep:`380` - Syntax for Delegating to a Subgenerator
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500511 The proposal to introduce the :token:`yield_from` syntax, making delegation
512 to sub-generators easy.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000513
Georg Brandl116aa622007-08-15 14:28:22 +0000514.. index:: object: generator
Yury Selivanov66f88282015-06-24 11:04:15 -0400515.. _generator-methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000516
R David Murray2c1d1d62012-08-17 20:48:59 -0400517Generator-iterator methods
518^^^^^^^^^^^^^^^^^^^^^^^^^^
519
520This subsection describes the methods of a generator iterator. They can
521be used to control the execution of a generator function.
522
523Note that calling any of the generator methods below when the generator
524is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526.. index:: exception: StopIteration
527
528
Georg Brandl96593ed2007-09-07 14:15:41 +0000529.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000530
Georg Brandl96593ed2007-09-07 14:15:41 +0000531 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500532 executed yield expression. When a generator function is resumed with a
533 :meth:`~generator.__next__` method, the current yield expression always
534 evaluates to :const:`None`. The execution then continues to the next yield
535 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300536 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500537 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000538 exception is raised.
539
540 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
541 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000542
543
544.. method:: generator.send(value)
545
546 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500547 *value* argument becomes the result of the current yield expression. The
548 :meth:`send` method returns the next value yielded by the generator, or
549 raises :exc:`StopIteration` if the generator exits without yielding another
550 value. When :meth:`send` is called to start the generator, it must be called
551 with :const:`None` as the argument, because there is no yield expression that
552 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000553
554
555.. method:: generator.throw(type[, value[, traceback]])
556
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700557 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000558 and returns the next value yielded by the generator function. If the generator
559 exits without yielding another value, a :exc:`StopIteration` exception is
560 raised. If the generator function does not catch the passed-in exception, or
561 raises a different exception, then that exception propagates to the caller.
562
563.. index:: exception: GeneratorExit
564
565
566.. method:: generator.close()
567
568 Raises a :exc:`GeneratorExit` at the point where the generator function was
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400569 paused. If the generator function then exits gracefully, is already closed,
570 or raises :exc:`GeneratorExit` (by not catching the exception), close
571 returns to its caller. If the generator yields a value, a
572 :exc:`RuntimeError` is raised. If the generator raises any other exception,
573 it is propagated to the caller. :meth:`close` does nothing if the generator
574 has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000575
Chris Jerdonek2654b862012-12-23 15:31:57 -0800576.. index:: single: yield; examples
577
578Examples
579^^^^^^^^
580
Georg Brandl116aa622007-08-15 14:28:22 +0000581Here is a simple example that demonstrates the behavior of generators and
582generator functions::
583
584 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000585 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000586 ... try:
587 ... while True:
588 ... try:
589 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000590 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000591 ... value = e
592 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000593 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000594 ...
595 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000596 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000597 Execution starts when 'next()' is called for the first time.
598 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000599 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000600 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000601 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000602 2
603 >>> generator.throw(TypeError, "spam")
604 TypeError('spam',)
605 >>> generator.close()
606 Don't forget to clean up when 'close()' is called.
607
Chris Jerdonek2654b862012-12-23 15:31:57 -0800608For examples using ``yield from``, see :ref:`pep-380` in "What's New in
609Python."
610
Yury Selivanov03660042016-12-15 17:36:05 -0500611.. _asynchronous-generator-functions:
612
613Asynchronous generator functions
614^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
615
616The presence of a yield expression in a function or method defined using
617:keyword:`async def` further defines the function as a
618:term:`asynchronous generator` function.
619
620When an asynchronous generator function is called, it returns an
621asynchronous iterator known as an asynchronous generator object.
622That object then controls the execution of the generator function.
623An asynchronous generator object is typically used in an
624:keyword:`async for` statement in a coroutine function analogously to
625how a generator object would be used in a :keyword:`for` statement.
626
627Calling one of the asynchronous generator's methods returns an
628:term:`awaitable` object, and the execution starts when this object
629is awaited on. At that time, the execution proceeds to the first yield
630expression, where it is suspended again, returning the value of
631:token:`expression_list` to the awaiting coroutine. As with a generator,
632suspension means that all local state is retained, including the
633current bindings of local variables, the instruction pointer, the internal
634evaluation stack, and the state of any exception handling. When the execution
635is resumed by awaiting on the next object returned by the asynchronous
636generator's methods, the function can proceed exactly as if the yield
637expression were just another external call. The value of the yield expression
638after resuming depends on the method which resumed the execution. If
639:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
640:meth:`~agen.asend` is used, then the result will be the value passed in to
641that method.
642
643In an asynchronous generator function, yield expressions are allowed anywhere
644in a :keyword:`try` construct. However, if an asynchronous generator is not
645resumed before it is finalized (by reaching a zero reference count or by
646being garbage collected), then a yield expression within a :keyword:`try`
647construct could result in a failure to execute pending :keyword:`finally`
648clauses. In this case, it is the responsibility of the event loop or
649scheduler running the asynchronous generator to call the asynchronous
650generator-iterator's :meth:`~agen.aclose` method and run the resulting
651coroutine object, thus allowing any pending :keyword:`finally` clauses
652to execute.
653
654To take care of finalization, an event loop should define
655a *finalizer* function which takes an asynchronous generator-iterator
656and presumably calls :meth:`~agen.aclose` and executes the coroutine.
657This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`.
658When first iterated over, an asynchronous generator-iterator will store the
659registered *finalizer* to be called upon finalization. For a reference example
660of a *finalizer* method see the implementation of
661``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`.
662
663The expression ``yield from <expr>`` is a syntax error when used in an
664asynchronous generator function.
665
666.. index:: object: asynchronous-generator
667.. _asynchronous-generator-methods:
668
669Asynchronous generator-iterator methods
670^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
671
672This subsection describes the methods of an asynchronous generator iterator,
673which are used to control the execution of a generator function.
674
675
676.. index:: exception: StopAsyncIteration
677
678.. coroutinemethod:: agen.__anext__()
679
680 Returns an awaitable which when run starts to execute the asynchronous
681 generator or resumes it at the last executed yield expression. When an
682 asynchronous generator function is resumed with a :meth:`~agen.__anext__`
683 method, the current yield expression always evaluates to :const:`None` in
684 the returned awaitable, which when run will continue to the next yield
685 expression. The value of the :token:`expression_list` of the yield
686 expression is the value of the :exc:`StopIteration` exception raised by
687 the completing coroutine. If the asynchronous generator exits without
688 yielding another value, the awaitable instead raises an
689 :exc:`StopAsyncIteration` exception, signalling that the asynchronous
690 iteration has completed.
691
692 This method is normally called implicitly by a :keyword:`async for` loop.
693
694
695.. coroutinemethod:: agen.asend(value)
696
697 Returns an awaitable which when run resumes the execution of the
698 asynchronous generator. As with the :meth:`~generator.send()` method for a
699 generator, this "sends" a value into the asynchronous generator function,
700 and the *value* argument becomes the result of the current yield expression.
701 The awaitable returned by the :meth:`asend` method will return the next
702 value yielded by the generator as the value of the raised
703 :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the
704 asynchronous generator exits without yielding another value. When
705 :meth:`asend` is called to start the asynchronous
706 generator, it must be called with :const:`None` as the argument,
707 because there is no yield expression that could receive the value.
708
709
710.. coroutinemethod:: agen.athrow(type[, value[, traceback]])
711
712 Returns an awaitable that raises an exception of type ``type`` at the point
713 where the asynchronous generator was paused, and returns the next value
714 yielded by the generator function as the value of the raised
715 :exc:`StopIteration` exception. If the asynchronous generator exits
716 without yielding another value, an :exc:`StopAsyncIteration` exception is
717 raised by the awaitable.
718 If the generator function does not catch the passed-in exception, or
delirious-lettuce3378b202017-05-19 14:37:57 -0600719 raises a different exception, then when the awaitable is run that exception
Yury Selivanov03660042016-12-15 17:36:05 -0500720 propagates to the caller of the awaitable.
721
722.. index:: exception: GeneratorExit
723
724
725.. coroutinemethod:: agen.aclose()
726
727 Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
728 the asynchronous generator function at the point where it was paused.
729 If the asynchronous generator function then exits gracefully, is already
730 closed, or raises :exc:`GeneratorExit` (by not catching the exception),
731 then the returned awaitable will raise a :exc:`StopIteration` exception.
732 Any further awaitables returned by subsequent calls to the asynchronous
733 generator will raise a :exc:`StopAsyncIteration` exception. If the
734 asynchronous generator yields a value, a :exc:`RuntimeError` is raised
735 by the awaitable. If the asynchronous generator raises any other exception,
736 it is propagated to the caller of the awaitable. If the asynchronous
737 generator has already exited due to an exception or normal exit, then
738 further calls to :meth:`aclose` will return an awaitable that does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000739
Georg Brandl116aa622007-08-15 14:28:22 +0000740.. _primaries:
741
742Primaries
743=========
744
745.. index:: single: primary
746
747Primaries represent the most tightly bound operations of the language. Their
748syntax is:
749
750.. productionlist::
751 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
752
753
754.. _attribute-references:
755
756Attribute references
757--------------------
758
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300759.. index::
760 pair: attribute; reference
761 single: .; attribute reference
Georg Brandl116aa622007-08-15 14:28:22 +0000762
763An attribute reference is a primary followed by a period and a name:
764
765.. productionlist::
766 attributeref: `primary` "." `identifier`
767
768.. index::
769 exception: AttributeError
770 object: module
771 object: list
772
773The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000774references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700775attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500776overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700777the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
778the object produced is determined by the object. Multiple evaluations of the
779same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000780
781
782.. _subscriptions:
783
784Subscriptions
785-------------
786
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300787.. index::
788 single: subscription
789 single: [; subscription
790 single: ]; subscription
Georg Brandl116aa622007-08-15 14:28:22 +0000791
792.. index::
793 object: sequence
794 object: mapping
795 object: string
796 object: tuple
797 object: list
798 object: dictionary
799 pair: sequence; item
800
801A subscription selects an item of a sequence (string, tuple or list) or mapping
802(dictionary) object:
803
804.. productionlist::
805 subscription: `primary` "[" `expression_list` "]"
806
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700807The primary must evaluate to an object that supports subscription (lists or
808dictionaries for example). User-defined objects can support subscription by
809defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000810
811For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000812
813If the primary is a mapping, the expression list must evaluate to an object
814whose value is one of the keys of the mapping, and the subscription selects the
815value in the mapping that corresponds to that key. (The expression list is a
816tuple except if it has exactly one item.)
817
Miss Islington (bot)01133912018-06-15 11:45:37 -0700818If the primary is a sequence, the expression list must evaluate to an integer
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000819or a slice (as discussed in the following section).
820
821The formal syntax makes no special provision for negative indices in
822sequences; however, built-in sequences all provide a :meth:`__getitem__`
823method that interprets negative indices by adding the length of the sequence
824to the index (so that ``x[-1]`` selects the last item of ``x``). The
825resulting value must be a nonnegative integer less than the number of items in
826the sequence, and the subscription selects the item whose index is that value
827(counting from zero). Since the support for negative indices and slicing
828occurs in the object's :meth:`__getitem__` method, subclasses overriding
829this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000830
831.. index::
832 single: character
833 pair: string; item
834
835A string's items are characters. A character is not a separate data type but a
836string of exactly one character.
837
838
839.. _slicings:
840
841Slicings
842--------
843
844.. index::
845 single: slicing
846 single: slice
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300847 single: :; slicing
848 single: ,; slicing
Georg Brandl116aa622007-08-15 14:28:22 +0000849
850.. index::
851 object: sequence
852 object: string
853 object: tuple
854 object: list
855
856A slicing selects a range of items in a sequence object (e.g., a string, tuple
857or list). Slicings may be used as expressions or as targets in assignment or
858:keyword:`del` statements. The syntax for a slicing:
859
860.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000861 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000862 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000863 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000864 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000865 lower_bound: `expression`
866 upper_bound: `expression`
867 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000868
869There is ambiguity in the formal syntax here: anything that looks like an
870expression list also looks like a slice list, so any subscription can be
871interpreted as a slicing. Rather than further complicating the syntax, this is
872disambiguated by defining that in this case the interpretation as a subscription
873takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000874slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000875
876.. index::
877 single: start (slice object attribute)
878 single: stop (slice object attribute)
879 single: step (slice object attribute)
880
Georg Brandla4c8c472014-10-31 10:38:49 +0100881The semantics for a slicing are as follows. The primary is indexed (using the
882same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000883normal subscription) with a key that is constructed from the slice list, as
884follows. If the slice list contains at least one comma, the key is a tuple
885containing the conversion of the slice items; otherwise, the conversion of the
886lone slice item is the key. The conversion of a slice item that is an
887expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300888object (see section :ref:`types`) whose :attr:`~slice.start`,
889:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
890expressions given as lower bound, upper bound and stride, respectively,
891substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000892
893
Chris Jerdonekb4309942012-12-25 14:54:44 -0800894.. index::
895 object: callable
896 single: call
897 single: argument; call semantics
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300898 single: (; call
899 single: ); call
900 single: ,; argument list
901 single: =; in function calls
Chris Jerdonekb4309942012-12-25 14:54:44 -0800902
Georg Brandl116aa622007-08-15 14:28:22 +0000903.. _calls:
904
905Calls
906-----
907
Chris Jerdonekb4309942012-12-25 14:54:44 -0800908A call calls a callable object (e.g., a :term:`function`) with a possibly empty
909series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000910
911.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000912 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Martin Panter0c0da482016-06-12 01:46:50 +0000913 argument_list: `positional_arguments` ["," `starred_and_keywords`]
914 : ["," `keywords_arguments`]
915 : | `starred_and_keywords` ["," `keywords_arguments`]
916 : | `keywords_arguments`
917 positional_arguments: ["*"] `expression` ("," ["*"] `expression`)*
918 starred_and_keywords: ("*" `expression` | `keyword_item`)
919 : ("," "*" `expression` | "," `keyword_item`)*
920 keywords_arguments: (`keyword_item` | "**" `expression`)
Martin Panter7106a512016-12-24 10:20:38 +0000921 : ("," `keyword_item` | "," "**" `expression`)*
Georg Brandl116aa622007-08-15 14:28:22 +0000922 keyword_item: `identifier` "=" `expression`
923
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700924An optional trailing comma may be present after the positional and keyword arguments
925but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000926
Chris Jerdonekb4309942012-12-25 14:54:44 -0800927.. index::
928 single: parameter; call semantics
929
Georg Brandl116aa622007-08-15 14:28:22 +0000930The primary must evaluate to a callable object (user-defined functions, built-in
931functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000932instances, and all objects having a :meth:`__call__` method are callable). All
933argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800934to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000935
936.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000937
938If keyword arguments are present, they are first converted to positional
939arguments, as follows. First, a list of unfilled slots is created for the
940formal parameters. If there are N positional arguments, they are placed in the
941first N slots. Next, for each keyword argument, the identifier is used to
942determine the corresponding slot (if the identifier is the same as the first
943formal parameter name, the first slot is used, and so on). If the slot is
944already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
945the argument is placed in the slot, filling it (even if the expression is
946``None``, it fills the slot). When all arguments have been processed, the slots
947that are still unfilled are filled with the corresponding default value from the
948function definition. (Default values are calculated, once, when the function is
949defined; thus, a mutable object such as a list or dictionary used as default
950value will be shared by all calls that don't specify an argument value for the
951corresponding slot; this should usually be avoided.) If there are any unfilled
952slots for which no default value is specified, a :exc:`TypeError` exception is
953raised. Otherwise, the list of filled slots is used as the argument list for
954the call.
955
Georg Brandl495f7b52009-10-27 15:28:25 +0000956.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000957
Georg Brandl495f7b52009-10-27 15:28:25 +0000958 An implementation may provide built-in functions whose positional parameters
959 do not have names, even if they are 'named' for the purpose of documentation,
960 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000961 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000962 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000963
Georg Brandl116aa622007-08-15 14:28:22 +0000964If there are more positional arguments than there are formal parameter slots, a
965:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
966``*identifier`` is present; in this case, that formal parameter receives a tuple
967containing the excess positional arguments (or an empty tuple if there were no
968excess positional arguments).
969
970If any keyword argument does not correspond to a formal parameter name, a
971:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
972``**identifier`` is present; in this case, that formal parameter receives a
973dictionary containing the excess keyword arguments (using the keywords as keys
974and the argument values as corresponding values), or a (new) empty dictionary if
975there were no excess keyword arguments.
976
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300977.. index::
978 single: *; in function calls
Martin Panter0c0da482016-06-12 01:46:50 +0000979 single: unpacking; in function calls
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300980
Georg Brandl116aa622007-08-15 14:28:22 +0000981If the syntax ``*expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +0000982evaluate to an :term:`iterable`. Elements from these iterables are
983treated as if they were additional positional arguments. For the call
984``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*,
985this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
986*y1*, ..., *yM*, *x3*, *x4*.
Georg Brandl116aa622007-08-15 14:28:22 +0000987
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000988A consequence of this is that although the ``*expression`` syntax may appear
Martin Panter0c0da482016-06-12 01:46:50 +0000989*after* explicit keyword arguments, it is processed *before* the
990keyword arguments (and any ``**expression`` arguments -- see below). So::
Georg Brandl116aa622007-08-15 14:28:22 +0000991
992 >>> def f(a, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300993 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000994 ...
995 >>> f(b=1, *(2,))
996 2 1
997 >>> f(a=1, *(2,))
998 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530999 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +00001000 TypeError: f() got multiple values for keyword argument 'a'
1001 >>> f(1, *(2,))
1002 1 2
1003
1004It is unusual for both keyword arguments and the ``*expression`` syntax to be
1005used in the same call, so in practice this confusion does not arise.
1006
Eli Bendersky7bd081c2011-07-30 07:05:16 +03001007.. index::
1008 single: **; in function calls
1009
Georg Brandl116aa622007-08-15 14:28:22 +00001010If the syntax ``**expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +00001011evaluate to a :term:`mapping`, the contents of which are treated as
1012additional keyword arguments. If a keyword is already present
1013(as an explicit keyword argument, or from another unpacking),
1014a :exc:`TypeError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001015
1016Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
1017used as positional argument slots or as keyword argument names.
1018
Martin Panter0c0da482016-06-12 01:46:50 +00001019.. versionchanged:: 3.5
1020 Function calls accept any number of ``*`` and ``**`` unpackings,
1021 positional arguments may follow iterable unpackings (``*``),
1022 and keyword arguments may follow dictionary unpackings (``**``).
1023 Originally proposed by :pep:`448`.
1024
Georg Brandl116aa622007-08-15 14:28:22 +00001025A call always returns some value, possibly ``None``, unless it raises an
1026exception. How this value is computed depends on the type of the callable
1027object.
1028
1029If it is---
1030
1031a user-defined function:
1032 .. index::
1033 pair: function; call
1034 triple: user-defined; function; call
1035 object: user-defined function
1036 object: function
1037
1038 The code block for the function is executed, passing it the argument list. The
1039 first thing the code block will do is bind the formal parameters to the
1040 arguments; this is described in section :ref:`function`. When the code block
1041 executes a :keyword:`return` statement, this specifies the return value of the
1042 function call.
1043
1044a built-in function or method:
1045 .. index::
1046 pair: function; call
1047 pair: built-in function; call
1048 pair: method; call
1049 pair: built-in method; call
1050 object: built-in method
1051 object: built-in function
1052 object: method
1053 object: function
1054
1055 The result is up to the interpreter; see :ref:`built-in-funcs` for the
1056 descriptions of built-in functions and methods.
1057
1058a class object:
1059 .. index::
1060 object: class
1061 pair: class object; call
1062
1063 A new instance of that class is returned.
1064
1065a class instance method:
1066 .. index::
1067 object: class instance
1068 object: instance
1069 pair: class instance; call
1070
1071 The corresponding user-defined function is called, with an argument list that is
1072 one longer than the argument list of the call: the instance becomes the first
1073 argument.
1074
1075a class instance:
1076 .. index::
1077 pair: instance; call
1078 single: __call__() (object method)
1079
1080 The class must define a :meth:`__call__` method; the effect is then the same as
1081 if that method was called.
1082
1083
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001084.. index:: keyword: await
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001085.. _await:
1086
1087Await expression
1088================
1089
1090Suspend the execution of :term:`coroutine` on an :term:`awaitable` object.
1091Can only be used inside a :term:`coroutine function`.
1092
1093.. productionlist::
Serhiy Storchakac7cc9852016-05-08 21:59:46 +03001094 await_expr: "await" `primary`
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001095
1096.. versionadded:: 3.5
1097
1098
Georg Brandl116aa622007-08-15 14:28:22 +00001099.. _power:
1100
1101The power operator
1102==================
1103
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001104.. index::
1105 pair: power; operation
1106 operator: **
1107
Georg Brandl116aa622007-08-15 14:28:22 +00001108The power operator binds more tightly than unary operators on its left; it binds
1109less tightly than unary operators on its right. The syntax is:
1110
1111.. productionlist::
Miss Islington (bot)80c188f2018-07-07 14:09:09 -07001112 power: (`await_expr` | `primary`) ["**" `u_expr`]
Georg Brandl116aa622007-08-15 14:28:22 +00001113
1114Thus, in an unparenthesized sequence of power and unary operators, the operators
1115are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +00001116for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001117
1118The power operator has the same semantics as the built-in :func:`pow` function,
1119when called with two arguments: it yields its left argument raised to the power
1120of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +00001121type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +00001122
Georg Brandl96593ed2007-09-07 14:15:41 +00001123For int operands, the result has the same type as the operands unless the second
1124argument is negative; in that case, all arguments are converted to float and a
1125float result is delivered. For example, ``10**2`` returns ``100``, but
1126``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +00001127
1128Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +00001129Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001130number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001131
1132
1133.. _unary:
1134
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001135Unary arithmetic and bitwise operations
1136=======================================
Georg Brandl116aa622007-08-15 14:28:22 +00001137
1138.. index::
1139 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +00001140 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001141
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001142All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +00001143
1144.. productionlist::
1145 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
1146
1147.. index::
1148 single: negation
1149 single: minus
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001150 single: operator; -
1151 single: -; unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001152
1153The unary ``-`` (minus) operator yields the negation of its numeric argument.
1154
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001155.. index::
1156 single: plus
1157 single: operator; +
1158 single: +; unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001159
1160The unary ``+`` (plus) operator yields its numeric argument unchanged.
1161
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001162.. index::
1163 single: inversion
1164 operator: ~
Christian Heimesfaf2f632008-01-06 16:59:19 +00001165
Georg Brandl95817b32008-05-11 14:30:18 +00001166The unary ``~`` (invert) operator yields the bitwise inversion of its integer
1167argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
1168applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00001169
1170.. index:: exception: TypeError
1171
1172In all three cases, if the argument does not have the proper type, a
1173:exc:`TypeError` exception is raised.
1174
1175
1176.. _binary:
1177
1178Binary arithmetic operations
1179============================
1180
1181.. index:: triple: binary; arithmetic; operation
1182
1183The binary arithmetic operations have the conventional priority levels. Note
1184that some of these operations also apply to certain non-numeric types. Apart
1185from the power operator, there are only two levels, one for multiplicative
1186operators and one for additive operators:
1187
1188.. productionlist::
Benjamin Petersond51374e2014-04-09 23:55:56 -04001189 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
Miss Islington (bot)80c188f2018-07-07 14:09:09 -07001190 : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` |
Benjamin Petersond51374e2014-04-09 23:55:56 -04001191 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001192 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
1193
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001194.. index::
1195 single: multiplication
1196 operator: *
Georg Brandl116aa622007-08-15 14:28:22 +00001197
1198The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +00001199arguments must either both be numbers, or one argument must be an integer and
1200the other must be a sequence. In the former case, the numbers are converted to a
1201common type and then multiplied together. In the latter case, sequence
1202repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001203
Miss Islington (bot)c05c0e02018-06-15 12:42:30 -07001204.. index::
1205 single: matrix multiplication
1206 operator: @
Benjamin Petersond51374e2014-04-09 23:55:56 -04001207
1208The ``@`` (at) operator is intended to be used for matrix multiplication. No
1209builtin Python types implement this operator.
1210
1211.. versionadded:: 3.5
1212
Georg Brandl116aa622007-08-15 14:28:22 +00001213.. index::
1214 exception: ZeroDivisionError
1215 single: division
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001216 operator: /
1217 operator: //
Georg Brandl116aa622007-08-15 14:28:22 +00001218
1219The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
1220their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +02001221Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +00001222integer; the result is that of mathematical division with the 'floor' function
1223applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
1224exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001225
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001226.. index::
1227 single: modulo
1228 operator: %
Georg Brandl116aa622007-08-15 14:28:22 +00001229
1230The ``%`` (modulo) operator yields the remainder from the division of the first
1231argument by the second. The numeric arguments are first converted to a common
1232type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
1233arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
1234(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
1235result with the same sign as its second operand (or zero); the absolute value of
1236the result is strictly smaller than the absolute value of the second operand
1237[#]_.
1238
Georg Brandl96593ed2007-09-07 14:15:41 +00001239The floor division and modulo operators are connected by the following
1240identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
1241connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
1242x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +00001243
1244In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +00001245also overloaded by string objects to perform old-style string formatting (also
1246known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +00001247Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +00001248
1249The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +00001250function are not defined for complex numbers. Instead, convert to a floating
1251point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +00001252
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001253.. index::
1254 single: addition
1255 single: operator; +
1256 single: +; binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001257
Georg Brandl96593ed2007-09-07 14:15:41 +00001258The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001259must either both be numbers or both be sequences of the same type. In the
1260former case, the numbers are converted to a common type and then added together.
1261In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +00001262
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001263.. index::
1264 single: subtraction
1265 single: operator; -
1266 single: -; binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001267
1268The ``-`` (subtraction) operator yields the difference of its arguments. The
1269numeric arguments are first converted to a common type.
1270
1271
1272.. _shifting:
1273
1274Shifting operations
1275===================
1276
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001277.. index::
1278 pair: shifting; operation
1279 operator: <<
1280 operator: >>
Georg Brandl116aa622007-08-15 14:28:22 +00001281
1282The shifting operations have lower priority than the arithmetic operations:
1283
1284.. productionlist::
Miss Islington (bot)80c188f2018-07-07 14:09:09 -07001285 shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001286
Georg Brandl96593ed2007-09-07 14:15:41 +00001287These operators accept integers as arguments. They shift the first argument to
1288the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001289
1290.. index:: exception: ValueError
1291
Georg Brandl0aaae262013-10-08 21:47:18 +02001292A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
1293shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001294
1295
1296.. _bitwise:
1297
Christian Heimesfaf2f632008-01-06 16:59:19 +00001298Binary bitwise operations
1299=========================
Georg Brandl116aa622007-08-15 14:28:22 +00001300
Christian Heimesfaf2f632008-01-06 16:59:19 +00001301.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001302
1303Each of the three bitwise operations has a different priority level:
1304
1305.. productionlist::
1306 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1307 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1308 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1309
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001310.. index::
1311 pair: bitwise; and
1312 operator: &
Georg Brandl116aa622007-08-15 14:28:22 +00001313
Georg Brandl96593ed2007-09-07 14:15:41 +00001314The ``&`` operator yields the bitwise AND of its arguments, which must be
1315integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001316
1317.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001318 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001319 pair: exclusive; or
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001320 operator: ^
Georg Brandl116aa622007-08-15 14:28:22 +00001321
1322The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001323must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001324
1325.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001326 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001327 pair: inclusive; or
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001328 operator: |
Georg Brandl116aa622007-08-15 14:28:22 +00001329
1330The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001331must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001332
1333
1334.. _comparisons:
1335
1336Comparisons
1337===========
1338
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001339.. index::
1340 single: comparison
1341 pair: C; language
1342 operator: <
1343 operator: >
1344 operator: <=
1345 operator: >=
1346 operator: ==
1347 operator: !=
Georg Brandl116aa622007-08-15 14:28:22 +00001348
1349Unlike C, all comparison operations in Python have the same priority, which is
1350lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1351C, expressions like ``a < b < c`` have the interpretation that is conventional
1352in mathematics:
1353
1354.. productionlist::
Miss Islington (bot)80c188f2018-07-07 14:09:09 -07001355 comparison: `or_expr` (`comp_operator` `or_expr`)*
Georg Brandl116aa622007-08-15 14:28:22 +00001356 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1357 : | "is" ["not"] | ["not"] "in"
1358
1359Comparisons yield boolean values: ``True`` or ``False``.
1360
1361.. index:: pair: chaining; comparisons
1362
1363Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1364``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1365cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1366
Guido van Rossum04110fb2007-08-24 16:32:05 +00001367Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1368*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1369to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1370evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001371
Guido van Rossum04110fb2007-08-24 16:32:05 +00001372Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001373*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1374pretty).
1375
Martin Panteraa0da862015-09-23 05:28:13 +00001376Value comparisons
1377-----------------
1378
Georg Brandl116aa622007-08-15 14:28:22 +00001379The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
Martin Panteraa0da862015-09-23 05:28:13 +00001380values of two objects. The objects do not need to have the same type.
Georg Brandl116aa622007-08-15 14:28:22 +00001381
Martin Panteraa0da862015-09-23 05:28:13 +00001382Chapter :ref:`objects` states that objects have a value (in addition to type
1383and identity). The value of an object is a rather abstract notion in Python:
1384For example, there is no canonical access method for an object's value. Also,
1385there is no requirement that the value of an object should be constructed in a
1386particular way, e.g. comprised of all its data attributes. Comparison operators
1387implement a particular notion of what the value of an object is. One can think
1388of them as defining the value of an object indirectly, by means of their
1389comparison implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00001390
Martin Panteraa0da862015-09-23 05:28:13 +00001391Because all types are (direct or indirect) subtypes of :class:`object`, they
1392inherit the default comparison behavior from :class:`object`. Types can
1393customize their comparison behavior by implementing
1394:dfn:`rich comparison methods` like :meth:`__lt__`, described in
1395:ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001396
Martin Panteraa0da862015-09-23 05:28:13 +00001397The default behavior for equality comparison (``==`` and ``!=``) is based on
1398the identity of the objects. Hence, equality comparison of instances with the
1399same identity results in equality, and equality comparison of instances with
1400different identities results in inequality. A motivation for this default
1401behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1402implies ``x == y``).
1403
1404A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1405an attempt raises :exc:`TypeError`. A motivation for this default behavior is
1406the lack of a similar invariant as for equality.
1407
1408The behavior of the default equality comparison, that instances with different
1409identities are always unequal, may be in contrast to what types will need that
1410have a sensible definition of object value and value-based equality. Such
1411types will need to customize their comparison behavior, and in fact, a number
1412of built-in types have done that.
1413
1414The following list describes the comparison behavior of the most important
1415built-in types.
1416
1417* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1418 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
1419 compared within and across their types, with the restriction that complex
1420 numbers do not support order comparison. Within the limits of the types
1421 involved, they compare mathematically (algorithmically) correct without loss
1422 of precision.
1423
Miss Islington (bot)ca2fa282018-09-14 11:05:38 -07001424 The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are
1425 special. Any ordered comparison of a number to a not-a-number value is false.
1426 A counter-intuitive implication is that not-a-number values are not equal to
1427 themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3``, ``x
1428 == x``, ``x != x`` are all false. This behavior is compliant with IEEE 754.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001429
Martin Panteraa0da862015-09-23 05:28:13 +00001430* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
1431 compared within and across their types. They compare lexicographically using
1432 the numeric values of their elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001433
Martin Panteraa0da862015-09-23 05:28:13 +00001434* Strings (instances of :class:`str`) compare lexicographically using the
1435 numerical Unicode code points (the result of the built-in function
1436 :func:`ord`) of their characters. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001437
Martin Panteraa0da862015-09-23 05:28:13 +00001438 Strings and binary sequences cannot be directly compared.
Georg Brandl116aa622007-08-15 14:28:22 +00001439
Martin Panteraa0da862015-09-23 05:28:13 +00001440* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can
1441 be compared only within each of their types, with the restriction that ranges
1442 do not support order comparison. Equality comparison across these types
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +02001443 results in inequality, and ordering comparison across these types raises
Martin Panteraa0da862015-09-23 05:28:13 +00001444 :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001445
Martin Panteraa0da862015-09-23 05:28:13 +00001446 Sequences compare lexicographically using comparison of corresponding
1447 elements, whereby reflexivity of the elements is enforced.
Georg Brandl116aa622007-08-15 14:28:22 +00001448
Martin Panteraa0da862015-09-23 05:28:13 +00001449 In enforcing reflexivity of elements, the comparison of collections assumes
1450 that for a collection element ``x``, ``x == x`` is always true. Based on
1451 that assumption, element identity is compared first, and element comparison
1452 is performed only for distinct elements. This approach yields the same
1453 result as a strict element comparison would, if the compared elements are
1454 reflexive. For non-reflexive elements, the result is different than for
1455 strict element comparison, and may be surprising: The non-reflexive
1456 not-a-number values for example result in the following comparison behavior
1457 when used in a list::
1458
1459 >>> nan = float('NaN')
1460 >>> nan is nan
1461 True
1462 >>> nan == nan
1463 False <-- the defined non-reflexive behavior of NaN
1464 >>> [nan] == [nan]
1465 True <-- list enforces reflexivity and tests identity first
1466
1467 Lexicographical comparison between built-in collections works as follows:
1468
1469 - For two collections to compare equal, they must be of the same type, have
1470 the same length, and each pair of corresponding elements must compare
1471 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1472 same).
1473
1474 - Collections that support order comparison are ordered the same as their
1475 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same
1476 value as ``x <= y``). If a corresponding element does not exist, the
1477 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1478 true).
1479
1480* Mappings (instances of :class:`dict`) compare equal if and only if they have
cocoatomocdcac032017-03-31 14:48:49 +09001481 equal `(key, value)` pairs. Equality comparison of the keys and values
Martin Panteraa0da862015-09-23 05:28:13 +00001482 enforces reflexivity.
1483
1484 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
1485
1486* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within
1487 and across their types.
1488
1489 They define order
1490 comparison operators to mean subset and superset tests. Those relations do
1491 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}``
1492 are not equal, nor subsets of one another, nor supersets of one
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001493 another). Accordingly, sets are not appropriate arguments for functions
Martin Panteraa0da862015-09-23 05:28:13 +00001494 which depend on total ordering (for example, :func:`min`, :func:`max`, and
1495 :func:`sorted` produce undefined results given a list of sets as inputs).
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001496
Martin Panteraa0da862015-09-23 05:28:13 +00001497 Comparison of sets enforces reflexivity of its elements.
Georg Brandl116aa622007-08-15 14:28:22 +00001498
Martin Panteraa0da862015-09-23 05:28:13 +00001499* Most other built-in types have no comparison methods implemented, so they
1500 inherit the default comparison behavior.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001501
Martin Panteraa0da862015-09-23 05:28:13 +00001502User-defined classes that customize their comparison behavior should follow
1503some consistency rules, if possible:
1504
1505* Equality comparison should be reflexive.
1506 In other words, identical objects should compare equal:
1507
1508 ``x is y`` implies ``x == y``
1509
1510* Comparison should be symmetric.
1511 In other words, the following expressions should have the same result:
1512
1513 ``x == y`` and ``y == x``
1514
1515 ``x != y`` and ``y != x``
1516
1517 ``x < y`` and ``y > x``
1518
1519 ``x <= y`` and ``y >= x``
1520
1521* Comparison should be transitive.
1522 The following (non-exhaustive) examples illustrate that:
1523
1524 ``x > y and y > z`` implies ``x > z``
1525
1526 ``x < y and y <= z`` implies ``x < z``
1527
1528* Inverse comparison should result in the boolean negation.
1529 In other words, the following expressions should have the same result:
1530
1531 ``x == y`` and ``not x != y``
1532
1533 ``x < y`` and ``not x >= y`` (for total ordering)
1534
1535 ``x > y`` and ``not x <= y`` (for total ordering)
1536
1537 The last two expressions apply to totally ordered collections (e.g. to
1538 sequences, but not to sets or mappings). See also the
1539 :func:`~functools.total_ordering` decorator.
1540
Martin Panter8dbb0ca2017-01-29 10:00:23 +00001541* The :func:`hash` result should be consistent with equality.
1542 Objects that are equal should either have the same hash value,
1543 or be marked as unhashable.
1544
Martin Panteraa0da862015-09-23 05:28:13 +00001545Python does not enforce these consistency rules. In fact, the not-a-number
1546values are an example for not following these rules.
1547
1548
1549.. _in:
1550.. _not in:
Georg Brandl495f7b52009-10-27 15:28:25 +00001551.. _membership-test-details:
1552
Martin Panteraa0da862015-09-23 05:28:13 +00001553Membership test operations
1554--------------------------
1555
Georg Brandl96593ed2007-09-07 14:15:41 +00001556The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301557s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
1558``x not in s`` returns the negation of ``x in s``. All built-in sequences and
1559set types support this as well as dictionary, for which :keyword:`in` tests
1560whether the dictionary has a given key. For container types such as list, tuple,
1561set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001562to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001563
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301564For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
Georg Brandl4b491312007-08-31 09:22:56 +00001565substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1566always considered to be a substring of any other string, so ``"" in "abc"`` will
1567return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001568
Georg Brandl116aa622007-08-15 14:28:22 +00001569For user-defined classes which define the :meth:`__contains__` method, ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301570y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and
1571``False`` otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001572
Georg Brandl495f7b52009-10-27 15:28:25 +00001573For user-defined classes which do not define :meth:`__contains__` but do define
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301574:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z`` with ``x == z`` is
Georg Brandl495f7b52009-10-27 15:28:25 +00001575produced while iterating over ``y``. If an exception is raised during the
1576iteration, it is as if :keyword:`in` raised that exception.
1577
1578Lastly, the old-style iteration protocol is tried: if a class defines
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301579:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
Georg Brandl116aa622007-08-15 14:28:22 +00001580integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001581raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001582if :keyword:`in` raised that exception).
1583
1584.. index::
1585 operator: in
1586 operator: not in
1587 pair: membership; test
1588 object: sequence
1589
1590The operator :keyword:`not in` is defined to have the inverse true value of
1591:keyword:`in`.
1592
1593.. index::
1594 operator: is
1595 operator: is not
1596 pair: identity; test
1597
Martin Panteraa0da862015-09-23 05:28:13 +00001598
1599.. _is:
1600.. _is not:
1601
1602Identity comparisons
1603--------------------
1604
Georg Brandl116aa622007-08-15 14:28:22 +00001605The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
Raymond Hettinger06e18a72016-09-11 17:23:49 -07001606is y`` is true if and only if *x* and *y* are the same object. Object identity
1607is determined using the :meth:`id` function. ``x is not y`` yields the inverse
1608truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001609
1610
1611.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001612.. _and:
1613.. _or:
1614.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001615
1616Boolean operations
1617==================
1618
1619.. index::
1620 pair: Conditional; expression
1621 pair: Boolean; operation
1622
Georg Brandl116aa622007-08-15 14:28:22 +00001623.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001624 or_test: `and_test` | `or_test` "or" `and_test`
1625 and_test: `not_test` | `and_test` "and" `not_test`
1626 not_test: `comparison` | "not" `not_test`
1627
1628In the context of Boolean operations, and also when expressions are used by
1629control flow statements, the following values are interpreted as false:
1630``False``, ``None``, numeric zero of all types, and empty strings and containers
1631(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001632other values are interpreted as true. User-defined objects can customize their
1633truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001634
1635.. index:: operator: not
1636
1637The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1638otherwise.
1639
Georg Brandl116aa622007-08-15 14:28:22 +00001640.. index:: operator: and
1641
1642The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1643returned; otherwise, *y* is evaluated and the resulting value is returned.
1644
1645.. index:: operator: or
1646
1647The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1648returned; otherwise, *y* is evaluated and the resulting value is returned.
1649
1650(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1651they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001652argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001653replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001654the desired value. Because :keyword:`not` has to create a new value, it
1655returns a boolean value regardless of the type of its argument
1656(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001657
1658
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001659Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001660=======================
1661
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001662.. index::
1663 pair: conditional; expression
1664 pair: ternary; operator
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001665 single: if; conditional expression
1666 single: else; conditional expression
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001667
1668.. productionlist::
1669 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001670 expression: `conditional_expression` | `lambda_expr`
1671 expression_nocond: `or_test` | `lambda_expr_nocond`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001672
1673Conditional expressions (sometimes called a "ternary operator") have the lowest
1674priority of all Python operations.
1675
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001676The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1677If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001678evaluated and its value is returned.
1679
1680See :pep:`308` for more details about conditional expressions.
1681
1682
Georg Brandl116aa622007-08-15 14:28:22 +00001683.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001684.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001685
1686Lambdas
1687=======
1688
1689.. index::
1690 pair: lambda; expression
1691 pair: lambda; form
1692 pair: anonymous; function
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001693 single: :; lambda expression
Georg Brandl116aa622007-08-15 14:28:22 +00001694
1695.. productionlist::
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001696 lambda_expr: "lambda" [`parameter_list`] ":" `expression`
1697 lambda_expr_nocond: "lambda" [`parameter_list`] ":" `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001698
Zachary Ware2f78b842014-06-03 09:32:40 -05001699Lambda expressions (sometimes called lambda forms) are used to create anonymous
Miss Islington (bot)d9055f82018-05-22 01:07:28 -07001700functions. The expression ``lambda parameters: expression`` yields a function
Martin Panter1050d2d2016-07-26 11:18:21 +02001701object. The unnamed object behaves like a function object defined with:
1702
1703.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +00001704
Miss Islington (bot)d9055f82018-05-22 01:07:28 -07001705 def <lambda>(parameters):
Georg Brandl116aa622007-08-15 14:28:22 +00001706 return expression
1707
1708See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001709functions created with lambda expressions cannot contain statements or
1710annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001711
Georg Brandl116aa622007-08-15 14:28:22 +00001712
1713.. _exprlists:
1714
1715Expression lists
1716================
1717
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001718.. index::
1719 pair: expression; list
1720 single: comma; expression list
1721 single: ,; expression list
Georg Brandl116aa622007-08-15 14:28:22 +00001722
1723.. productionlist::
Miss Islington (bot)80c188f2018-07-07 14:09:09 -07001724 expression_list: `expression` ("," `expression`)* [","]
1725 starred_list: `starred_item` ("," `starred_item`)* [","]
1726 starred_expression: `expression` | (`starred_item` ",")* [`starred_item`]
Martin Panter0c0da482016-06-12 01:46:50 +00001727 starred_item: `expression` | "*" `or_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001728
1729.. index:: object: tuple
1730
Martin Panter0c0da482016-06-12 01:46:50 +00001731Except when part of a list or set display, an expression list
1732containing at least one comma yields a tuple. The length of
Georg Brandl116aa622007-08-15 14:28:22 +00001733the tuple is the number of expressions in the list. The expressions are
1734evaluated from left to right.
1735
Martin Panter0c0da482016-06-12 01:46:50 +00001736.. index::
1737 pair: iterable; unpacking
1738 single: *; in expression lists
1739
1740An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be
1741an :term:`iterable`. The iterable is expanded into a sequence of items,
1742which are included in the new tuple, list, or set, at the site of
1743the unpacking.
1744
1745.. versionadded:: 3.5
1746 Iterable unpacking in expression lists, originally proposed by :pep:`448`.
1747
Georg Brandl116aa622007-08-15 14:28:22 +00001748.. index:: pair: trailing; comma
1749
1750The trailing comma is required only to create a single tuple (a.k.a. a
1751*singleton*); it is optional in all other cases. A single expression without a
1752trailing comma doesn't create a tuple, but rather yields the value of that
1753expression. (To create an empty tuple, use an empty pair of parentheses:
1754``()``.)
1755
1756
1757.. _evalorder:
1758
1759Evaluation order
1760================
1761
1762.. index:: pair: evaluation; order
1763
Georg Brandl96593ed2007-09-07 14:15:41 +00001764Python evaluates expressions from left to right. Notice that while evaluating
1765an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001766
1767In the following lines, expressions will be evaluated in the arithmetic order of
1768their suffixes::
1769
1770 expr1, expr2, expr3, expr4
1771 (expr1, expr2, expr3, expr4)
1772 {expr1: expr2, expr3: expr4}
1773 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001774 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001775 expr3, expr4 = expr1, expr2
1776
1777
1778.. _operator-summary:
1779
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001780Operator precedence
1781===================
Georg Brandl116aa622007-08-15 14:28:22 +00001782
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001783.. index::
1784 pair: operator; precedence
Georg Brandl116aa622007-08-15 14:28:22 +00001785
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001786The following table summarizes the operator precedence in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001787precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001788the same box have the same precedence. Unless the syntax is explicitly given,
1789operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001790exponentiation, which groups from right to left).
1791
1792Note that comparisons, membership tests, and identity tests, all have the same
1793precedence and have a left-to-right chaining feature as described in the
1794:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001795
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001796
1797+-----------------------------------------------+-------------------------------------+
1798| Operator | Description |
1799+===============================================+=====================================+
1800| :keyword:`lambda` | Lambda expression |
1801+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001802| :keyword:`if` -- :keyword:`else` | Conditional expression |
1803+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001804| :keyword:`or` | Boolean OR |
1805+-----------------------------------------------+-------------------------------------+
1806| :keyword:`and` | Boolean AND |
1807+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001808| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001809+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001810| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001811| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001812| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001813+-----------------------------------------------+-------------------------------------+
1814| ``|`` | Bitwise OR |
1815+-----------------------------------------------+-------------------------------------+
1816| ``^`` | Bitwise XOR |
1817+-----------------------------------------------+-------------------------------------+
1818| ``&`` | Bitwise AND |
1819+-----------------------------------------------+-------------------------------------+
1820| ``<<``, ``>>`` | Shifts |
1821+-----------------------------------------------+-------------------------------------+
1822| ``+``, ``-`` | Addition and subtraction |
1823+-----------------------------------------------+-------------------------------------+
Benjamin Petersond51374e2014-04-09 23:55:56 -04001824| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
svelankar9b47af62017-09-17 20:56:16 -04001825| | multiplication, division, floor |
1826| | division, remainder [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001827+-----------------------------------------------+-------------------------------------+
1828| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1829+-----------------------------------------------+-------------------------------------+
1830| ``**`` | Exponentiation [#]_ |
1831+-----------------------------------------------+-------------------------------------+
Serhiy Storchaka9a75b842018-10-26 11:18:42 +03001832| :keyword:`await` ``x`` | Await expression |
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001833+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001834| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1835| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1836+-----------------------------------------------+-------------------------------------+
1837| ``(expressions...)``, | Binding or tuple display, |
1838| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001839| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001840| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001841+-----------------------------------------------+-------------------------------------+
1842
Georg Brandl116aa622007-08-15 14:28:22 +00001843
1844.. rubric:: Footnotes
1845
Georg Brandl116aa622007-08-15 14:28:22 +00001846.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1847 true numerically due to roundoff. For example, and assuming a platform on which
1848 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1849 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001850 1e100``, which is numerically exactly equal to ``1e100``. The function
1851 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001852 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1853 is more appropriate depends on the application.
1854
1855.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001856 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001857 cases, Python returns the latter result, in order to preserve that
1858 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1859
Martin Panteraa0da862015-09-23 05:28:13 +00001860.. [#] The Unicode standard distinguishes between :dfn:`code points`
1861 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
1862 While most abstract characters in Unicode are only represented using one
1863 code point, there is a number of abstract characters that can in addition be
1864 represented using a sequence of more than one code point. For example, the
1865 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
1866 as a single :dfn:`precomposed character` at code position U+00C7, or as a
1867 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
1868 LETTER C), followed by a :dfn:`combining character` at code position U+0327
1869 (COMBINING CEDILLA).
1870
1871 The comparison operators on strings compare at the level of Unicode code
1872 points. This may be counter-intuitive to humans. For example,
1873 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1874 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".
1875
1876 To compare strings at the level of abstract characters (that is, in a way
1877 intuitive to humans), use :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001878
Georg Brandl48310cd2009-01-03 21:18:54 +00001879.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001880 descriptors, you may notice seemingly unusual behaviour in certain uses of
1881 the :keyword:`is` operator, like those involving comparisons between instance
1882 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001883
Georg Brandl063f2372010-12-01 15:32:43 +00001884.. [#] The ``%`` operator is also used for string formatting; the same
1885 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001886
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001887.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1888 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.