blob: fdbbba123b60ba607b7882d1edf8678d9e56d6f6 [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 Storchakaddb961d2018-10-26 09:00:49 +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 Storchakaddb961d2018-10-26 09:00:49 +0300152 single: comma; tuple display
Georg Brandl116aa622007-08-15 14:28:22 +0000153 pair: tuple; display
Serhiy Storchakaddb961d2018-10-26 09:00:49 +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 Storchakaddb961d2018-10-26 09:00:49 +0300175.. index::
176 single: for; in comprehensions
177 single: if; in comprehensions
178 single: async for; in comprehensions
179
Georg Brandl96593ed2007-09-07 14:15:41 +0000180Common syntax elements for comprehensions are:
181
182.. productionlist::
183 comprehension: `expression` `comp_for`
Serhiy Storchakad08972f2018-04-11 19:15:51 +0300184 comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`]
Georg Brandl96593ed2007-09-07 14:15:41 +0000185 comp_iter: `comp_for` | `comp_if`
186 comp_if: "if" `expression_nocond` [`comp_iter`]
187
188The comprehension consists of a single expression followed by at least one
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
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200208nested scope.
Georg Brandl02c30562007-09-07 17:52:53 +0000209
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300210.. index::
211 single: await; in comprehensions
212
Yury Selivanov03660042016-12-15 17:36:05 -0500213Since Python 3.6, in an :keyword:`async def` function, an :keyword:`async for`
214clause may be used to iterate over a :term:`asynchronous iterator`.
215A comprehension in an :keyword:`async def` function may consist of either a
216:keyword:`for` or :keyword:`async for` clause following the leading
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +0200217expression, may contain additional :keyword:`for` or :keyword:`async for`
Yury Selivanov03660042016-12-15 17:36:05 -0500218clauses, and may also use :keyword:`await` expressions.
219If a comprehension contains either :keyword:`async for` clauses
220or :keyword:`await` expressions it is called an
221:dfn:`asynchronous comprehension`. An asynchronous comprehension may
222suspend the execution of the coroutine function in which it appears.
223See also :pep:`530`.
Georg Brandl96593ed2007-09-07 14:15:41 +0000224
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200225.. versionadded:: 3.6
226 Asynchronous comprehensions were introduced.
227
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200228.. versionchanged:: 3.8
229 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200230
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232.. _lists:
233
234List displays
235-------------
236
237.. index::
238 pair: list; display
239 pair: list; comprehensions
Georg Brandl96593ed2007-09-07 14:15:41 +0000240 pair: empty; list
241 object: list
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300242 single: [; list expression
243 single: ]; list expression
244 single: ,; expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246A list display is a possibly empty series of expressions enclosed in square
247brackets:
248
249.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000250 list_display: "[" [`starred_list` | `comprehension`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000251
Georg Brandl96593ed2007-09-07 14:15:41 +0000252A list display yields a new list object, the contents being specified by either
253a list of expressions or a comprehension. When a comma-separated list of
254expressions is supplied, its elements are evaluated from left to right and
255placed into the list object in that order. When a comprehension is supplied,
256the list is constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000257
258
Georg Brandl96593ed2007-09-07 14:15:41 +0000259.. _set:
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Georg Brandl96593ed2007-09-07 14:15:41 +0000261Set displays
262------------
Georg Brandl116aa622007-08-15 14:28:22 +0000263
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300264.. index::
265 pair: set; display
266 object: set
267 single: {; set expression
268 single: }; set expression
269 single: ,; expression list
Georg Brandl116aa622007-08-15 14:28:22 +0000270
Georg Brandl96593ed2007-09-07 14:15:41 +0000271A set display is denoted by curly braces and distinguishable from dictionary
272displays by the lack of colons separating keys and values:
Georg Brandl116aa622007-08-15 14:28:22 +0000273
274.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +0000275 set_display: "{" (`starred_list` | `comprehension`) "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000276
Georg Brandl96593ed2007-09-07 14:15:41 +0000277A set display yields a new mutable set object, the contents being specified by
278either a sequence of expressions or a comprehension. When a comma-separated
279list of expressions is supplied, its elements are evaluated from left to right
280and added to the set object. When a comprehension is supplied, the set is
281constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
Georg Brandl528cdb12008-09-21 07:09:51 +0000283An empty set cannot be constructed with ``{}``; this literal constructs an empty
284dictionary.
Christian Heimes78644762008-03-04 23:39:23 +0000285
286
Georg Brandl116aa622007-08-15 14:28:22 +0000287.. _dict:
288
289Dictionary displays
290-------------------
291
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300292.. index::
293 pair: dictionary; display
294 key, datum, key/datum pair
295 object: dictionary
296 single: {; dictionary expression
297 single: }; dictionary expression
298 single: :; in dictionary expressions
299 single: ,; in dictionary displays
Georg Brandl116aa622007-08-15 14:28:22 +0000300
301A dictionary display is a possibly empty series of key/datum pairs enclosed in
302curly braces:
303
304.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000305 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000306 key_datum_list: `key_datum` ("," `key_datum`)* [","]
Martin Panter0c0da482016-06-12 01:46:50 +0000307 key_datum: `expression` ":" `expression` | "**" `or_expr`
Georg Brandl96593ed2007-09-07 14:15:41 +0000308 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000309
310A dictionary display yields a new dictionary object.
311
Georg Brandl96593ed2007-09-07 14:15:41 +0000312If a comma-separated sequence of key/datum pairs is given, they are evaluated
313from left to right to define the entries of the dictionary: each key object is
314used as a key into the dictionary to store the corresponding datum. This means
315that you can specify the same key multiple times in the key/datum list, and the
316final dictionary's value for that key will be the last one given.
317
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300318.. index::
319 unpacking; dictionary
320 single: **; in dictionary displays
Martin Panter0c0da482016-06-12 01:46:50 +0000321
322A double asterisk ``**`` denotes :dfn:`dictionary unpacking`.
323Its operand must be a :term:`mapping`. Each mapping item is added
324to the new dictionary. Later values replace values already set by
325earlier key/datum pairs and earlier dictionary unpackings.
326
327.. versionadded:: 3.5
328 Unpacking into dictionary displays, originally proposed by :pep:`448`.
329
Georg Brandl96593ed2007-09-07 14:15:41 +0000330A dict comprehension, in contrast to list and set comprehensions, needs two
331expressions separated with a colon followed by the usual "for" and "if" clauses.
332When the comprehension is run, the resulting key and value elements are inserted
333in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000334
335.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000336 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000339:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000340all mutable objects.) Clashes between duplicate keys are not detected; the last
341datum (textually rightmost in the display) stored for a given key value
342prevails.
343
344
Georg Brandl96593ed2007-09-07 14:15:41 +0000345.. _genexpr:
346
347Generator expressions
348---------------------
349
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300350.. index::
351 pair: generator; expression
352 object: generator
353 single: (; generator expression
354 single: ); generator expression
Georg Brandl96593ed2007-09-07 14:15:41 +0000355
356A generator expression is a compact generator notation in parentheses:
357
358.. productionlist::
359 generator_expression: "(" `expression` `comp_for` ")"
360
361A generator expression yields a new generator object. Its syntax is the same as
362for comprehensions, except that it is enclosed in parentheses instead of
363brackets or curly braces.
364
365Variables used in the generator expression are evaluated lazily when the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700366:meth:`~generator.__next__` method is called for the generator object (in the same
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200367fashion as normal generators). However, the iterable expression in the
368leftmost :keyword:`for` clause is immediately evaluated, so that an error
369produced by it will be emitted at the point where the generator expression
370is defined, rather than at the point where the first value is retrieved.
371Subsequent :keyword:`for` clauses and any filter condition in the leftmost
372:keyword:`for` clause cannot be evaluated in the enclosing scope as they may
373depend on the values obtained from the leftmost iterable. For example:
374``(x*y for x in range(10) for y in range(x, x+10))``.
Georg Brandl96593ed2007-09-07 14:15:41 +0000375
376The parentheses can be omitted on calls with only one argument. See section
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700377:ref:`calls` for details.
Georg Brandl96593ed2007-09-07 14:15:41 +0000378
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200379To avoid interfering with the expected operation of the generator expression
380itself, ``yield`` and ``yield from`` expressions are prohibited in the
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200381implicitly defined generator.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200382
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400383If a generator expression contains either :keyword:`async for`
384clauses or :keyword:`await` expressions it is called an
385:dfn:`asynchronous generator expression`. An asynchronous generator
386expression returns a new asynchronous generator object,
387which is an asynchronous iterator (see :ref:`async-iterators`).
388
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200389.. versionadded:: 3.6
390 Asynchronous generator expressions were introduced.
391
Yury Selivanovb8ab9d32017-10-06 02:58:28 -0400392.. versionchanged:: 3.7
393 Prior to Python 3.7, asynchronous generator expressions could
394 only appear in :keyword:`async def` coroutines. Starting
395 with 3.7, any function can use asynchronous generator expressions.
Georg Brandl96593ed2007-09-07 14:15:41 +0000396
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200397.. versionchanged:: 3.8
398 ``yield`` and ``yield from`` prohibited in the implicitly nested scope.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200399
400
Georg Brandl116aa622007-08-15 14:28:22 +0000401.. _yieldexpr:
402
403Yield expressions
404-----------------
405
406.. index::
407 keyword: yield
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300408 keyword: from
Georg Brandl116aa622007-08-15 14:28:22 +0000409 pair: yield; expression
410 pair: generator; function
411
412.. productionlist::
413 yield_atom: "(" `yield_expression` ")"
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000414 yield_expression: "yield" [`expression_list` | "from" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Yury Selivanov03660042016-12-15 17:36:05 -0500416The yield expression is used when defining a :term:`generator` function
417or an :term:`asynchronous generator` function and
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500418thus can only be used in the body of a function definition. Using a yield
Yury Selivanov03660042016-12-15 17:36:05 -0500419expression in a function's body causes that function to be a generator,
420and using it in an :keyword:`async def` function's body causes that
421coroutine function to be an asynchronous generator. For example::
422
423 def gen(): # defines a generator function
424 yield 123
425
426 async def agen(): # defines an asynchronous generator function (PEP 525)
427 yield 123
428
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200429Due to their side effects on the containing scope, ``yield`` expressions
430are not permitted as part of the implicitly defined scopes used to
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200431implement comprehensions and generator expressions.
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200432
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +0200433.. versionchanged:: 3.8
434 Yield expressions prohibited in the implicitly nested scopes used to
Serhiy Storchaka73a7e9b2017-12-01 06:54:17 +0200435 implement comprehensions and generator expressions.
436
Yury Selivanov03660042016-12-15 17:36:05 -0500437Generator functions are described below, while asynchronous generator
438functions are described separately in section
439:ref:`asynchronous-generator-functions`.
Georg Brandl116aa622007-08-15 14:28:22 +0000440
441When a generator function is called, it returns an iterator known as a
Guido van Rossumd0150ad2015-05-05 12:02:01 -0700442generator. That generator then controls the execution of the generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000443The execution starts when one of the generator's methods is called. At that
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500444time, the execution proceeds to the first yield expression, where it is
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700445suspended again, returning the value of :token:`expression_list` to the generator's
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500446caller. By suspended, we mean that all local state is retained, including the
Ethan Furman2f825af2015-01-14 22:25:27 -0800447current bindings of local variables, the instruction pointer, the internal
448evaluation stack, and the state of any exception handling. When the execution
449is resumed by calling one of the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500450generator's methods, the function can proceed exactly as if the yield expression
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700451were just another external call. The value of the yield expression after
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500452resuming depends on the method which resumed the execution. If
453:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or
454the :func:`next` builtin) then the result is :const:`None`. Otherwise, if
455:meth:`~generator.send` is used, then the result will be the value passed in to
456that method.
Georg Brandl116aa622007-08-15 14:28:22 +0000457
458.. index:: single: coroutine
459
460All of this makes generator functions quite similar to coroutines; they yield
461multiple times, they have more than one entry point and their execution can be
462suspended. The only difference is that a generator function cannot control
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700463where the execution should continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000464transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000465
Ethan Furman2f825af2015-01-14 22:25:27 -0800466Yield expressions are allowed anywhere in a :keyword:`try` construct. If the
467generator is not resumed before it is
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500468finalized (by reaching a zero reference count or by being garbage collected),
469the generator-iterator's :meth:`~generator.close` method will be called,
470allowing any pending :keyword:`finally` clauses to execute.
Georg Brandl02c30562007-09-07 17:52:53 +0000471
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300472.. index::
473 single: from; yield from expression
474
Nick Coghlan0ed80192012-01-14 14:43:24 +1000475When ``yield from <expr>`` is used, it treats the supplied expression as
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000476a subiterator. All values produced by that subiterator are passed directly
477to the caller of the current generator's methods. Any values passed in with
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300478:meth:`~generator.send` and any exceptions passed in with
479:meth:`~generator.throw` are passed to the underlying iterator if it has the
480appropriate methods. If this is not the case, then :meth:`~generator.send`
481will raise :exc:`AttributeError` or :exc:`TypeError`, while
482:meth:`~generator.throw` will just raise the passed in exception immediately.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000483
484When the underlying iterator is complete, the :attr:`~StopIteration.value`
485attribute of the raised :exc:`StopIteration` instance becomes the value of
486the yield expression. It can be either set explicitly when raising
487:exc:`StopIteration`, or automatically when the sub-iterator is a generator
488(by returning a value from the sub-generator).
489
Nick Coghlan0ed80192012-01-14 14:43:24 +1000490 .. versionchanged:: 3.3
Martin Panterd21e0b52015-10-10 10:36:22 +0000491 Added ``yield from <expr>`` to delegate control flow to a subiterator.
Nick Coghlan0ed80192012-01-14 14:43:24 +1000492
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500493The parentheses may be omitted when the yield expression is the sole expression
494on the right hand side of an assignment statement.
495
496.. seealso::
497
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300498 :pep:`255` - Simple Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500499 The proposal for adding generators and the :keyword:`yield` statement to Python.
500
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300501 :pep:`342` - Coroutines via Enhanced Generators
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500502 The proposal to enhance the API and syntax of generators, making them
503 usable as simple coroutines.
504
Serhiy Storchakae4ba8722016-03-31 15:30:54 +0300505 :pep:`380` - Syntax for Delegating to a Subgenerator
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500506 The proposal to introduce the :token:`yield_from` syntax, making delegation
507 to sub-generators easy.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000508
Georg Brandl116aa622007-08-15 14:28:22 +0000509.. index:: object: generator
Yury Selivanov66f88282015-06-24 11:04:15 -0400510.. _generator-methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000511
R David Murray2c1d1d62012-08-17 20:48:59 -0400512Generator-iterator methods
513^^^^^^^^^^^^^^^^^^^^^^^^^^
514
515This subsection describes the methods of a generator iterator. They can
516be used to control the execution of a generator function.
517
518Note that calling any of the generator methods below when the generator
519is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521.. index:: exception: StopIteration
522
523
Georg Brandl96593ed2007-09-07 14:15:41 +0000524.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000525
Georg Brandl96593ed2007-09-07 14:15:41 +0000526 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500527 executed yield expression. When a generator function is resumed with a
528 :meth:`~generator.__next__` method, the current yield expression always
529 evaluates to :const:`None`. The execution then continues to the next yield
530 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300531 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500532 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000533 exception is raised.
534
535 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
536 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000537
538
539.. method:: generator.send(value)
540
541 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500542 *value* argument becomes the result of the current yield expression. The
543 :meth:`send` method returns the next value yielded by the generator, or
544 raises :exc:`StopIteration` if the generator exits without yielding another
545 value. When :meth:`send` is called to start the generator, it must be called
546 with :const:`None` as the argument, because there is no yield expression that
547 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000548
549
550.. method:: generator.throw(type[, value[, traceback]])
551
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700552 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000553 and returns the next value yielded by the generator function. If the generator
554 exits without yielding another value, a :exc:`StopIteration` exception is
555 raised. If the generator function does not catch the passed-in exception, or
556 raises a different exception, then that exception propagates to the caller.
557
558.. index:: exception: GeneratorExit
559
560
561.. method:: generator.close()
562
563 Raises a :exc:`GeneratorExit` at the point where the generator function was
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400564 paused. If the generator function then exits gracefully, is already closed,
565 or raises :exc:`GeneratorExit` (by not catching the exception), close
566 returns to its caller. If the generator yields a value, a
567 :exc:`RuntimeError` is raised. If the generator raises any other exception,
568 it is propagated to the caller. :meth:`close` does nothing if the generator
569 has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000570
Chris Jerdonek2654b862012-12-23 15:31:57 -0800571.. index:: single: yield; examples
572
573Examples
574^^^^^^^^
575
Georg Brandl116aa622007-08-15 14:28:22 +0000576Here is a simple example that demonstrates the behavior of generators and
577generator functions::
578
579 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000580 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000581 ... try:
582 ... while True:
583 ... try:
584 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000585 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000586 ... value = e
587 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000588 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000589 ...
590 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000591 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000592 Execution starts when 'next()' is called for the first time.
593 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000594 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000595 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000596 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000597 2
598 >>> generator.throw(TypeError, "spam")
599 TypeError('spam',)
600 >>> generator.close()
601 Don't forget to clean up when 'close()' is called.
602
Chris Jerdonek2654b862012-12-23 15:31:57 -0800603For examples using ``yield from``, see :ref:`pep-380` in "What's New in
604Python."
605
Yury Selivanov03660042016-12-15 17:36:05 -0500606.. _asynchronous-generator-functions:
607
608Asynchronous generator functions
609^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
610
611The presence of a yield expression in a function or method defined using
612:keyword:`async def` further defines the function as a
613:term:`asynchronous generator` function.
614
615When an asynchronous generator function is called, it returns an
616asynchronous iterator known as an asynchronous generator object.
617That object then controls the execution of the generator function.
618An asynchronous generator object is typically used in an
619:keyword:`async for` statement in a coroutine function analogously to
620how a generator object would be used in a :keyword:`for` statement.
621
622Calling one of the asynchronous generator's methods returns an
623:term:`awaitable` object, and the execution starts when this object
624is awaited on. At that time, the execution proceeds to the first yield
625expression, where it is suspended again, returning the value of
626:token:`expression_list` to the awaiting coroutine. As with a generator,
627suspension means that all local state is retained, including the
628current bindings of local variables, the instruction pointer, the internal
629evaluation stack, and the state of any exception handling. When the execution
630is resumed by awaiting on the next object returned by the asynchronous
631generator's methods, the function can proceed exactly as if the yield
632expression were just another external call. The value of the yield expression
633after resuming depends on the method which resumed the execution. If
634:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
635:meth:`~agen.asend` is used, then the result will be the value passed in to
636that method.
637
638In an asynchronous generator function, yield expressions are allowed anywhere
639in a :keyword:`try` construct. However, if an asynchronous generator is not
640resumed before it is finalized (by reaching a zero reference count or by
641being garbage collected), then a yield expression within a :keyword:`try`
642construct could result in a failure to execute pending :keyword:`finally`
643clauses. In this case, it is the responsibility of the event loop or
644scheduler running the asynchronous generator to call the asynchronous
645generator-iterator's :meth:`~agen.aclose` method and run the resulting
646coroutine object, thus allowing any pending :keyword:`finally` clauses
647to execute.
648
649To take care of finalization, an event loop should define
650a *finalizer* function which takes an asynchronous generator-iterator
651and presumably calls :meth:`~agen.aclose` and executes the coroutine.
652This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`.
653When first iterated over, an asynchronous generator-iterator will store the
654registered *finalizer* to be called upon finalization. For a reference example
655of a *finalizer* method see the implementation of
656``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`.
657
658The expression ``yield from <expr>`` is a syntax error when used in an
659asynchronous generator function.
660
661.. index:: object: asynchronous-generator
662.. _asynchronous-generator-methods:
663
664Asynchronous generator-iterator methods
665^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
666
667This subsection describes the methods of an asynchronous generator iterator,
668which are used to control the execution of a generator function.
669
670
671.. index:: exception: StopAsyncIteration
672
673.. coroutinemethod:: agen.__anext__()
674
675 Returns an awaitable which when run starts to execute the asynchronous
676 generator or resumes it at the last executed yield expression. When an
677 asynchronous generator function is resumed with a :meth:`~agen.__anext__`
678 method, the current yield expression always evaluates to :const:`None` in
679 the returned awaitable, which when run will continue to the next yield
680 expression. The value of the :token:`expression_list` of the yield
681 expression is the value of the :exc:`StopIteration` exception raised by
682 the completing coroutine. If the asynchronous generator exits without
683 yielding another value, the awaitable instead raises an
684 :exc:`StopAsyncIteration` exception, signalling that the asynchronous
685 iteration has completed.
686
687 This method is normally called implicitly by a :keyword:`async for` loop.
688
689
690.. coroutinemethod:: agen.asend(value)
691
692 Returns an awaitable which when run resumes the execution of the
693 asynchronous generator. As with the :meth:`~generator.send()` method for a
694 generator, this "sends" a value into the asynchronous generator function,
695 and the *value* argument becomes the result of the current yield expression.
696 The awaitable returned by the :meth:`asend` method will return the next
697 value yielded by the generator as the value of the raised
698 :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the
699 asynchronous generator exits without yielding another value. When
700 :meth:`asend` is called to start the asynchronous
701 generator, it must be called with :const:`None` as the argument,
702 because there is no yield expression that could receive the value.
703
704
705.. coroutinemethod:: agen.athrow(type[, value[, traceback]])
706
707 Returns an awaitable that raises an exception of type ``type`` at the point
708 where the asynchronous generator was paused, and returns the next value
709 yielded by the generator function as the value of the raised
710 :exc:`StopIteration` exception. If the asynchronous generator exits
711 without yielding another value, an :exc:`StopAsyncIteration` exception is
712 raised by the awaitable.
713 If the generator function does not catch the passed-in exception, or
delirious-lettuce3378b202017-05-19 14:37:57 -0600714 raises a different exception, then when the awaitable is run that exception
Yury Selivanov03660042016-12-15 17:36:05 -0500715 propagates to the caller of the awaitable.
716
717.. index:: exception: GeneratorExit
718
719
720.. coroutinemethod:: agen.aclose()
721
722 Returns an awaitable that when run will throw a :exc:`GeneratorExit` into
723 the asynchronous generator function at the point where it was paused.
724 If the asynchronous generator function then exits gracefully, is already
725 closed, or raises :exc:`GeneratorExit` (by not catching the exception),
726 then the returned awaitable will raise a :exc:`StopIteration` exception.
727 Any further awaitables returned by subsequent calls to the asynchronous
728 generator will raise a :exc:`StopAsyncIteration` exception. If the
729 asynchronous generator yields a value, a :exc:`RuntimeError` is raised
730 by the awaitable. If the asynchronous generator raises any other exception,
731 it is propagated to the caller of the awaitable. If the asynchronous
732 generator has already exited due to an exception or normal exit, then
733 further calls to :meth:`aclose` will return an awaitable that does nothing.
Georg Brandl116aa622007-08-15 14:28:22 +0000734
Georg Brandl116aa622007-08-15 14:28:22 +0000735.. _primaries:
736
737Primaries
738=========
739
740.. index:: single: primary
741
742Primaries represent the most tightly bound operations of the language. Their
743syntax is:
744
745.. productionlist::
746 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
747
748
749.. _attribute-references:
750
751Attribute references
752--------------------
753
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300754.. index::
755 pair: attribute; reference
756 single: .; attribute reference
Georg Brandl116aa622007-08-15 14:28:22 +0000757
758An attribute reference is a primary followed by a period and a name:
759
760.. productionlist::
761 attributeref: `primary` "." `identifier`
762
763.. index::
764 exception: AttributeError
765 object: module
766 object: list
767
768The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000769references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700770attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500771overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700772the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
773the object produced is determined by the object. Multiple evaluations of the
774same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000775
776
777.. _subscriptions:
778
779Subscriptions
780-------------
781
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300782.. index::
783 single: subscription
784 single: [; subscription
785 single: ]; subscription
Georg Brandl116aa622007-08-15 14:28:22 +0000786
787.. index::
788 object: sequence
789 object: mapping
790 object: string
791 object: tuple
792 object: list
793 object: dictionary
794 pair: sequence; item
795
796A subscription selects an item of a sequence (string, tuple or list) or mapping
797(dictionary) object:
798
799.. productionlist::
800 subscription: `primary` "[" `expression_list` "]"
801
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700802The primary must evaluate to an object that supports subscription (lists or
803dictionaries for example). User-defined objects can support subscription by
804defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000805
806For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000807
808If the primary is a mapping, the expression list must evaluate to an object
809whose value is one of the keys of the mapping, and the subscription selects the
810value in the mapping that corresponds to that key. (The expression list is a
811tuple except if it has exactly one item.)
812
Andrés Delfino4fddd4e2018-06-15 15:24:25 -0300813If the primary is a sequence, the expression list must evaluate to an integer
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000814or a slice (as discussed in the following section).
815
816The formal syntax makes no special provision for negative indices in
817sequences; however, built-in sequences all provide a :meth:`__getitem__`
818method that interprets negative indices by adding the length of the sequence
819to the index (so that ``x[-1]`` selects the last item of ``x``). The
820resulting value must be a nonnegative integer less than the number of items in
821the sequence, and the subscription selects the item whose index is that value
822(counting from zero). Since the support for negative indices and slicing
823occurs in the object's :meth:`__getitem__` method, subclasses overriding
824this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000825
826.. index::
827 single: character
828 pair: string; item
829
830A string's items are characters. A character is not a separate data type but a
831string of exactly one character.
832
833
834.. _slicings:
835
836Slicings
837--------
838
839.. index::
840 single: slicing
841 single: slice
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300842 single: :; slicing
843 single: ,; slicing
Georg Brandl116aa622007-08-15 14:28:22 +0000844
845.. index::
846 object: sequence
847 object: string
848 object: tuple
849 object: list
850
851A slicing selects a range of items in a sequence object (e.g., a string, tuple
852or list). Slicings may be used as expressions or as targets in assignment or
853:keyword:`del` statements. The syntax for a slicing:
854
855.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000856 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000857 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000858 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000859 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000860 lower_bound: `expression`
861 upper_bound: `expression`
862 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000863
864There is ambiguity in the formal syntax here: anything that looks like an
865expression list also looks like a slice list, so any subscription can be
866interpreted as a slicing. Rather than further complicating the syntax, this is
867disambiguated by defining that in this case the interpretation as a subscription
868takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000869slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000870
871.. index::
872 single: start (slice object attribute)
873 single: stop (slice object attribute)
874 single: step (slice object attribute)
875
Georg Brandla4c8c472014-10-31 10:38:49 +0100876The semantics for a slicing are as follows. The primary is indexed (using the
877same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000878normal subscription) with a key that is constructed from the slice list, as
879follows. If the slice list contains at least one comma, the key is a tuple
880containing the conversion of the slice items; otherwise, the conversion of the
881lone slice item is the key. The conversion of a slice item that is an
882expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300883object (see section :ref:`types`) whose :attr:`~slice.start`,
884:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
885expressions given as lower bound, upper bound and stride, respectively,
886substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000887
888
Chris Jerdonekb4309942012-12-25 14:54:44 -0800889.. index::
890 object: callable
891 single: call
892 single: argument; call semantics
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300893 single: (; call
894 single: ); call
895 single: ,; argument list
896 single: =; in function calls
Chris Jerdonekb4309942012-12-25 14:54:44 -0800897
Georg Brandl116aa622007-08-15 14:28:22 +0000898.. _calls:
899
900Calls
901-----
902
Chris Jerdonekb4309942012-12-25 14:54:44 -0800903A call calls a callable object (e.g., a :term:`function`) with a possibly empty
904series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000905
906.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000907 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Martin Panter0c0da482016-06-12 01:46:50 +0000908 argument_list: `positional_arguments` ["," `starred_and_keywords`]
909 : ["," `keywords_arguments`]
910 : | `starred_and_keywords` ["," `keywords_arguments`]
911 : | `keywords_arguments`
912 positional_arguments: ["*"] `expression` ("," ["*"] `expression`)*
913 starred_and_keywords: ("*" `expression` | `keyword_item`)
914 : ("," "*" `expression` | "," `keyword_item`)*
915 keywords_arguments: (`keyword_item` | "**" `expression`)
Martin Panter7106a512016-12-24 10:20:38 +0000916 : ("," `keyword_item` | "," "**" `expression`)*
Georg Brandl116aa622007-08-15 14:28:22 +0000917 keyword_item: `identifier` "=" `expression`
918
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700919An optional trailing comma may be present after the positional and keyword arguments
920but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000921
Chris Jerdonekb4309942012-12-25 14:54:44 -0800922.. index::
923 single: parameter; call semantics
924
Georg Brandl116aa622007-08-15 14:28:22 +0000925The primary must evaluate to a callable object (user-defined functions, built-in
926functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000927instances, and all objects having a :meth:`__call__` method are callable). All
928argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800929to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000930
931.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000932
933If keyword arguments are present, they are first converted to positional
934arguments, as follows. First, a list of unfilled slots is created for the
935formal parameters. If there are N positional arguments, they are placed in the
936first N slots. Next, for each keyword argument, the identifier is used to
937determine the corresponding slot (if the identifier is the same as the first
938formal parameter name, the first slot is used, and so on). If the slot is
939already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
940the argument is placed in the slot, filling it (even if the expression is
941``None``, it fills the slot). When all arguments have been processed, the slots
942that are still unfilled are filled with the corresponding default value from the
943function definition. (Default values are calculated, once, when the function is
944defined; thus, a mutable object such as a list or dictionary used as default
945value will be shared by all calls that don't specify an argument value for the
946corresponding slot; this should usually be avoided.) If there are any unfilled
947slots for which no default value is specified, a :exc:`TypeError` exception is
948raised. Otherwise, the list of filled slots is used as the argument list for
949the call.
950
Georg Brandl495f7b52009-10-27 15:28:25 +0000951.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000952
Georg Brandl495f7b52009-10-27 15:28:25 +0000953 An implementation may provide built-in functions whose positional parameters
954 do not have names, even if they are 'named' for the purpose of documentation,
955 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000956 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000957 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000958
Georg Brandl116aa622007-08-15 14:28:22 +0000959If there are more positional arguments than there are formal parameter slots, a
960:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
961``*identifier`` is present; in this case, that formal parameter receives a tuple
962containing the excess positional arguments (or an empty tuple if there were no
963excess positional arguments).
964
965If any keyword argument does not correspond to a formal parameter name, a
966:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
967``**identifier`` is present; in this case, that formal parameter receives a
968dictionary containing the excess keyword arguments (using the keywords as keys
969and the argument values as corresponding values), or a (new) empty dictionary if
970there were no excess keyword arguments.
971
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300972.. index::
973 single: *; in function calls
Martin Panter0c0da482016-06-12 01:46:50 +0000974 single: unpacking; in function calls
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300975
Georg Brandl116aa622007-08-15 14:28:22 +0000976If the syntax ``*expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +0000977evaluate to an :term:`iterable`. Elements from these iterables are
978treated as if they were additional positional arguments. For the call
979``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*,
980this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
981*y1*, ..., *yM*, *x3*, *x4*.
Georg Brandl116aa622007-08-15 14:28:22 +0000982
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000983A consequence of this is that although the ``*expression`` syntax may appear
Martin Panter0c0da482016-06-12 01:46:50 +0000984*after* explicit keyword arguments, it is processed *before* the
985keyword arguments (and any ``**expression`` arguments -- see below). So::
Georg Brandl116aa622007-08-15 14:28:22 +0000986
987 >>> def f(a, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300988 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000989 ...
990 >>> f(b=1, *(2,))
991 2 1
992 >>> f(a=1, *(2,))
993 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530994 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000995 TypeError: f() got multiple values for keyword argument 'a'
996 >>> f(1, *(2,))
997 1 2
998
999It is unusual for both keyword arguments and the ``*expression`` syntax to be
1000used in the same call, so in practice this confusion does not arise.
1001
Eli Bendersky7bd081c2011-07-30 07:05:16 +03001002.. index::
1003 single: **; in function calls
1004
Georg Brandl116aa622007-08-15 14:28:22 +00001005If the syntax ``**expression`` appears in the function call, ``expression`` must
Martin Panter0c0da482016-06-12 01:46:50 +00001006evaluate to a :term:`mapping`, the contents of which are treated as
1007additional keyword arguments. If a keyword is already present
1008(as an explicit keyword argument, or from another unpacking),
1009a :exc:`TypeError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001010
1011Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
1012used as positional argument slots or as keyword argument names.
1013
Martin Panter0c0da482016-06-12 01:46:50 +00001014.. versionchanged:: 3.5
1015 Function calls accept any number of ``*`` and ``**`` unpackings,
1016 positional arguments may follow iterable unpackings (``*``),
1017 and keyword arguments may follow dictionary unpackings (``**``).
1018 Originally proposed by :pep:`448`.
1019
Georg Brandl116aa622007-08-15 14:28:22 +00001020A call always returns some value, possibly ``None``, unless it raises an
1021exception. How this value is computed depends on the type of the callable
1022object.
1023
1024If it is---
1025
1026a user-defined function:
1027 .. index::
1028 pair: function; call
1029 triple: user-defined; function; call
1030 object: user-defined function
1031 object: function
1032
1033 The code block for the function is executed, passing it the argument list. The
1034 first thing the code block will do is bind the formal parameters to the
1035 arguments; this is described in section :ref:`function`. When the code block
1036 executes a :keyword:`return` statement, this specifies the return value of the
1037 function call.
1038
1039a built-in function or method:
1040 .. index::
1041 pair: function; call
1042 pair: built-in function; call
1043 pair: method; call
1044 pair: built-in method; call
1045 object: built-in method
1046 object: built-in function
1047 object: method
1048 object: function
1049
1050 The result is up to the interpreter; see :ref:`built-in-funcs` for the
1051 descriptions of built-in functions and methods.
1052
1053a class object:
1054 .. index::
1055 object: class
1056 pair: class object; call
1057
1058 A new instance of that class is returned.
1059
1060a class instance method:
1061 .. index::
1062 object: class instance
1063 object: instance
1064 pair: class instance; call
1065
1066 The corresponding user-defined function is called, with an argument list that is
1067 one longer than the argument list of the call: the instance becomes the first
1068 argument.
1069
1070a class instance:
1071 .. index::
1072 pair: instance; call
1073 single: __call__() (object method)
1074
1075 The class must define a :meth:`__call__` method; the effect is then the same as
1076 if that method was called.
1077
1078
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001079.. index:: keyword: await
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001080.. _await:
1081
1082Await expression
1083================
1084
1085Suspend the execution of :term:`coroutine` on an :term:`awaitable` object.
1086Can only be used inside a :term:`coroutine function`.
1087
1088.. productionlist::
Serhiy Storchakac7cc9852016-05-08 21:59:46 +03001089 await_expr: "await" `primary`
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001090
1091.. versionadded:: 3.5
1092
1093
Georg Brandl116aa622007-08-15 14:28:22 +00001094.. _power:
1095
1096The power operator
1097==================
1098
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001099.. index::
1100 pair: power; operation
1101 operator: **
1102
Georg Brandl116aa622007-08-15 14:28:22 +00001103The power operator binds more tightly than unary operators on its left; it binds
1104less tightly than unary operators on its right. The syntax is:
1105
1106.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001107 power: (`await_expr` | `primary`) ["**" `u_expr`]
Georg Brandl116aa622007-08-15 14:28:22 +00001108
1109Thus, in an unparenthesized sequence of power and unary operators, the operators
1110are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +00001111for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001112
1113The power operator has the same semantics as the built-in :func:`pow` function,
1114when called with two arguments: it yields its left argument raised to the power
1115of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +00001116type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +00001117
Georg Brandl96593ed2007-09-07 14:15:41 +00001118For int operands, the result has the same type as the operands unless the second
1119argument is negative; in that case, all arguments are converted to float and a
1120float result is delivered. For example, ``10**2`` returns ``100``, but
1121``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +00001122
1123Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +00001124Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001125number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001126
1127
1128.. _unary:
1129
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001130Unary arithmetic and bitwise operations
1131=======================================
Georg Brandl116aa622007-08-15 14:28:22 +00001132
1133.. index::
1134 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +00001135 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001136
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001137All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +00001138
1139.. productionlist::
1140 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
1141
1142.. index::
1143 single: negation
1144 single: minus
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001145 single: operator; -
1146 single: -; unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001147
1148The unary ``-`` (minus) operator yields the negation of its numeric argument.
1149
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001150.. index::
1151 single: plus
1152 single: operator; +
1153 single: +; unary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001154
1155The unary ``+`` (plus) operator yields its numeric argument unchanged.
1156
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001157.. index::
1158 single: inversion
1159 operator: ~
Christian Heimesfaf2f632008-01-06 16:59:19 +00001160
Georg Brandl95817b32008-05-11 14:30:18 +00001161The unary ``~`` (invert) operator yields the bitwise inversion of its integer
1162argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
1163applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +00001164
1165.. index:: exception: TypeError
1166
1167In all three cases, if the argument does not have the proper type, a
1168:exc:`TypeError` exception is raised.
1169
1170
1171.. _binary:
1172
1173Binary arithmetic operations
1174============================
1175
1176.. index:: triple: binary; arithmetic; operation
1177
1178The binary arithmetic operations have the conventional priority levels. Note
1179that some of these operations also apply to certain non-numeric types. Apart
1180from the power operator, there are only two levels, one for multiplicative
1181operators and one for additive operators:
1182
1183.. productionlist::
Benjamin Petersond51374e2014-04-09 23:55:56 -04001184 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
Andrés Delfinocaccca782018-07-07 17:24:46 -03001185 : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` |
Benjamin Petersond51374e2014-04-09 23:55:56 -04001186 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001187 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
1188
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001189.. index::
1190 single: multiplication
1191 operator: *
Georg Brandl116aa622007-08-15 14:28:22 +00001192
1193The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +00001194arguments must either both be numbers, or one argument must be an integer and
1195the other must be a sequence. In the former case, the numbers are converted to a
1196common type and then multiplied together. In the latter case, sequence
1197repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001198
Andrés Delfino69511862018-06-15 16:23:00 -03001199.. index::
1200 single: matrix multiplication
1201 operator: @
Benjamin Petersond51374e2014-04-09 23:55:56 -04001202
1203The ``@`` (at) operator is intended to be used for matrix multiplication. No
1204builtin Python types implement this operator.
1205
1206.. versionadded:: 3.5
1207
Georg Brandl116aa622007-08-15 14:28:22 +00001208.. index::
1209 exception: ZeroDivisionError
1210 single: division
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001211 operator: /
1212 operator: //
Georg Brandl116aa622007-08-15 14:28:22 +00001213
1214The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
1215their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +02001216Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +00001217integer; the result is that of mathematical division with the 'floor' function
1218applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
1219exception.
Georg Brandl116aa622007-08-15 14:28:22 +00001220
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001221.. index::
1222 single: modulo
1223 operator: %
Georg Brandl116aa622007-08-15 14:28:22 +00001224
1225The ``%`` (modulo) operator yields the remainder from the division of the first
1226argument by the second. The numeric arguments are first converted to a common
1227type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
1228arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
1229(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
1230result with the same sign as its second operand (or zero); the absolute value of
1231the result is strictly smaller than the absolute value of the second operand
1232[#]_.
1233
Georg Brandl96593ed2007-09-07 14:15:41 +00001234The floor division and modulo operators are connected by the following
1235identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
1236connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
1237x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +00001238
1239In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +00001240also overloaded by string objects to perform old-style string formatting (also
1241known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +00001242Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +00001243
1244The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +00001245function are not defined for complex numbers. Instead, convert to a floating
1246point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +00001247
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001248.. index::
1249 single: addition
1250 single: operator; +
1251 single: +; binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001252
Georg Brandl96593ed2007-09-07 14:15:41 +00001253The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001254must either both be numbers or both be sequences of the same type. In the
1255former case, the numbers are converted to a common type and then added together.
1256In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +00001257
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001258.. index::
1259 single: subtraction
1260 single: operator; -
1261 single: -; binary operator
Georg Brandl116aa622007-08-15 14:28:22 +00001262
1263The ``-`` (subtraction) operator yields the difference of its arguments. The
1264numeric arguments are first converted to a common type.
1265
1266
1267.. _shifting:
1268
1269Shifting operations
1270===================
1271
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001272.. index::
1273 pair: shifting; operation
1274 operator: <<
1275 operator: >>
Georg Brandl116aa622007-08-15 14:28:22 +00001276
1277The shifting operations have lower priority than the arithmetic operations:
1278
1279.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001280 shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001281
Georg Brandl96593ed2007-09-07 14:15:41 +00001282These operators accept integers as arguments. They shift the first argument to
1283the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001284
1285.. index:: exception: ValueError
1286
Georg Brandl0aaae262013-10-08 21:47:18 +02001287A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
1288shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001289
1290
1291.. _bitwise:
1292
Christian Heimesfaf2f632008-01-06 16:59:19 +00001293Binary bitwise operations
1294=========================
Georg Brandl116aa622007-08-15 14:28:22 +00001295
Christian Heimesfaf2f632008-01-06 16:59:19 +00001296.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001297
1298Each of the three bitwise operations has a different priority level:
1299
1300.. productionlist::
1301 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1302 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1303 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1304
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001305.. index::
1306 pair: bitwise; and
1307 operator: &
Georg Brandl116aa622007-08-15 14:28:22 +00001308
Georg Brandl96593ed2007-09-07 14:15:41 +00001309The ``&`` operator yields the bitwise AND of its arguments, which must be
1310integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001311
1312.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001313 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001314 pair: exclusive; or
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001315 operator: ^
Georg Brandl116aa622007-08-15 14:28:22 +00001316
1317The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001318must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001319
1320.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001321 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001322 pair: inclusive; or
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001323 operator: |
Georg Brandl116aa622007-08-15 14:28:22 +00001324
1325The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001326must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001327
1328
1329.. _comparisons:
1330
1331Comparisons
1332===========
1333
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001334.. index::
1335 single: comparison
1336 pair: C; language
1337 operator: <
1338 operator: >
1339 operator: <=
1340 operator: >=
1341 operator: ==
1342 operator: !=
Georg Brandl116aa622007-08-15 14:28:22 +00001343
1344Unlike C, all comparison operations in Python have the same priority, which is
1345lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1346C, expressions like ``a < b < c`` have the interpretation that is conventional
1347in mathematics:
1348
1349.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001350 comparison: `or_expr` (`comp_operator` `or_expr`)*
Georg Brandl116aa622007-08-15 14:28:22 +00001351 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1352 : | "is" ["not"] | ["not"] "in"
1353
1354Comparisons yield boolean values: ``True`` or ``False``.
1355
1356.. index:: pair: chaining; comparisons
1357
1358Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1359``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1360cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1361
Guido van Rossum04110fb2007-08-24 16:32:05 +00001362Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1363*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1364to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1365evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001366
Guido van Rossum04110fb2007-08-24 16:32:05 +00001367Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001368*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1369pretty).
1370
Martin Panteraa0da862015-09-23 05:28:13 +00001371Value comparisons
1372-----------------
1373
Georg Brandl116aa622007-08-15 14:28:22 +00001374The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
Martin Panteraa0da862015-09-23 05:28:13 +00001375values of two objects. The objects do not need to have the same type.
Georg Brandl116aa622007-08-15 14:28:22 +00001376
Martin Panteraa0da862015-09-23 05:28:13 +00001377Chapter :ref:`objects` states that objects have a value (in addition to type
1378and identity). The value of an object is a rather abstract notion in Python:
1379For example, there is no canonical access method for an object's value. Also,
1380there is no requirement that the value of an object should be constructed in a
1381particular way, e.g. comprised of all its data attributes. Comparison operators
1382implement a particular notion of what the value of an object is. One can think
1383of them as defining the value of an object indirectly, by means of their
1384comparison implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00001385
Martin Panteraa0da862015-09-23 05:28:13 +00001386Because all types are (direct or indirect) subtypes of :class:`object`, they
1387inherit the default comparison behavior from :class:`object`. Types can
1388customize their comparison behavior by implementing
1389:dfn:`rich comparison methods` like :meth:`__lt__`, described in
1390:ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001391
Martin Panteraa0da862015-09-23 05:28:13 +00001392The default behavior for equality comparison (``==`` and ``!=``) is based on
1393the identity of the objects. Hence, equality comparison of instances with the
1394same identity results in equality, and equality comparison of instances with
1395different identities results in inequality. A motivation for this default
1396behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1397implies ``x == y``).
1398
1399A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1400an attempt raises :exc:`TypeError`. A motivation for this default behavior is
1401the lack of a similar invariant as for equality.
1402
1403The behavior of the default equality comparison, that instances with different
1404identities are always unequal, may be in contrast to what types will need that
1405have a sensible definition of object value and value-based equality. Such
1406types will need to customize their comparison behavior, and in fact, a number
1407of built-in types have done that.
1408
1409The following list describes the comparison behavior of the most important
1410built-in types.
1411
1412* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1413 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
1414 compared within and across their types, with the restriction that complex
1415 numbers do not support order comparison. Within the limits of the types
1416 involved, they compare mathematically (algorithmically) correct without loss
1417 of precision.
1418
Tony Fluryad8a0002018-09-14 18:48:50 +01001419 The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are
1420 special. Any ordered comparison of a number to a not-a-number value is false.
1421 A counter-intuitive implication is that not-a-number values are not equal to
1422 themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3``, ``x
1423 == x``, ``x != x`` are all false. This behavior is compliant with IEEE 754.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001424
Martin Panteraa0da862015-09-23 05:28:13 +00001425* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
1426 compared within and across their types. They compare lexicographically using
1427 the numeric values of their elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001428
Martin Panteraa0da862015-09-23 05:28:13 +00001429* Strings (instances of :class:`str`) compare lexicographically using the
1430 numerical Unicode code points (the result of the built-in function
1431 :func:`ord`) of their characters. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001432
Martin Panteraa0da862015-09-23 05:28:13 +00001433 Strings and binary sequences cannot be directly compared.
Georg Brandl116aa622007-08-15 14:28:22 +00001434
Martin Panteraa0da862015-09-23 05:28:13 +00001435* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can
1436 be compared only within each of their types, with the restriction that ranges
1437 do not support order comparison. Equality comparison across these types
Jim Fasarakis-Hilliard132ac382017-02-24 22:32:54 +02001438 results in inequality, and ordering comparison across these types raises
Martin Panteraa0da862015-09-23 05:28:13 +00001439 :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001440
Martin Panteraa0da862015-09-23 05:28:13 +00001441 Sequences compare lexicographically using comparison of corresponding
1442 elements, whereby reflexivity of the elements is enforced.
Georg Brandl116aa622007-08-15 14:28:22 +00001443
Martin Panteraa0da862015-09-23 05:28:13 +00001444 In enforcing reflexivity of elements, the comparison of collections assumes
1445 that for a collection element ``x``, ``x == x`` is always true. Based on
1446 that assumption, element identity is compared first, and element comparison
1447 is performed only for distinct elements. This approach yields the same
1448 result as a strict element comparison would, if the compared elements are
1449 reflexive. For non-reflexive elements, the result is different than for
1450 strict element comparison, and may be surprising: The non-reflexive
1451 not-a-number values for example result in the following comparison behavior
1452 when used in a list::
1453
1454 >>> nan = float('NaN')
1455 >>> nan is nan
1456 True
1457 >>> nan == nan
1458 False <-- the defined non-reflexive behavior of NaN
1459 >>> [nan] == [nan]
1460 True <-- list enforces reflexivity and tests identity first
1461
1462 Lexicographical comparison between built-in collections works as follows:
1463
1464 - For two collections to compare equal, they must be of the same type, have
1465 the same length, and each pair of corresponding elements must compare
1466 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1467 same).
1468
1469 - Collections that support order comparison are ordered the same as their
1470 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same
1471 value as ``x <= y``). If a corresponding element does not exist, the
1472 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1473 true).
1474
1475* Mappings (instances of :class:`dict`) compare equal if and only if they have
cocoatomocdcac032017-03-31 14:48:49 +09001476 equal `(key, value)` pairs. Equality comparison of the keys and values
Martin Panteraa0da862015-09-23 05:28:13 +00001477 enforces reflexivity.
1478
1479 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
1480
1481* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within
1482 and across their types.
1483
1484 They define order
1485 comparison operators to mean subset and superset tests. Those relations do
1486 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}``
1487 are not equal, nor subsets of one another, nor supersets of one
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001488 another). Accordingly, sets are not appropriate arguments for functions
Martin Panteraa0da862015-09-23 05:28:13 +00001489 which depend on total ordering (for example, :func:`min`, :func:`max`, and
1490 :func:`sorted` produce undefined results given a list of sets as inputs).
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001491
Martin Panteraa0da862015-09-23 05:28:13 +00001492 Comparison of sets enforces reflexivity of its elements.
Georg Brandl116aa622007-08-15 14:28:22 +00001493
Martin Panteraa0da862015-09-23 05:28:13 +00001494* Most other built-in types have no comparison methods implemented, so they
1495 inherit the default comparison behavior.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001496
Martin Panteraa0da862015-09-23 05:28:13 +00001497User-defined classes that customize their comparison behavior should follow
1498some consistency rules, if possible:
1499
1500* Equality comparison should be reflexive.
1501 In other words, identical objects should compare equal:
1502
1503 ``x is y`` implies ``x == y``
1504
1505* Comparison should be symmetric.
1506 In other words, the following expressions should have the same result:
1507
1508 ``x == y`` and ``y == x``
1509
1510 ``x != y`` and ``y != x``
1511
1512 ``x < y`` and ``y > x``
1513
1514 ``x <= y`` and ``y >= x``
1515
1516* Comparison should be transitive.
1517 The following (non-exhaustive) examples illustrate that:
1518
1519 ``x > y and y > z`` implies ``x > z``
1520
1521 ``x < y and y <= z`` implies ``x < z``
1522
1523* Inverse comparison should result in the boolean negation.
1524 In other words, the following expressions should have the same result:
1525
1526 ``x == y`` and ``not x != y``
1527
1528 ``x < y`` and ``not x >= y`` (for total ordering)
1529
1530 ``x > y`` and ``not x <= y`` (for total ordering)
1531
1532 The last two expressions apply to totally ordered collections (e.g. to
1533 sequences, but not to sets or mappings). See also the
1534 :func:`~functools.total_ordering` decorator.
1535
Martin Panter8dbb0ca2017-01-29 10:00:23 +00001536* The :func:`hash` result should be consistent with equality.
1537 Objects that are equal should either have the same hash value,
1538 or be marked as unhashable.
1539
Martin Panteraa0da862015-09-23 05:28:13 +00001540Python does not enforce these consistency rules. In fact, the not-a-number
1541values are an example for not following these rules.
1542
1543
1544.. _in:
1545.. _not in:
Georg Brandl495f7b52009-10-27 15:28:25 +00001546.. _membership-test-details:
1547
Martin Panteraa0da862015-09-23 05:28:13 +00001548Membership test operations
1549--------------------------
1550
Georg Brandl96593ed2007-09-07 14:15:41 +00001551The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301552s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
1553``x not in s`` returns the negation of ``x in s``. All built-in sequences and
1554set types support this as well as dictionary, for which :keyword:`in` tests
1555whether the dictionary has a given key. For container types such as list, tuple,
1556set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001557to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001558
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301559For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
Georg Brandl4b491312007-08-31 09:22:56 +00001560substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1561always considered to be a substring of any other string, so ``"" in "abc"`` will
1562return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001563
Georg Brandl116aa622007-08-15 14:28:22 +00001564For user-defined classes which define the :meth:`__contains__` method, ``x in
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301565y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and
1566``False`` otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001567
Georg Brandl495f7b52009-10-27 15:28:25 +00001568For user-defined classes which do not define :meth:`__contains__` but do define
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301569:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z`` with ``x == z`` is
Georg Brandl495f7b52009-10-27 15:28:25 +00001570produced while iterating over ``y``. If an exception is raised during the
1571iteration, it is as if :keyword:`in` raised that exception.
1572
1573Lastly, the old-style iteration protocol is tried: if a class defines
Amit Kumar0ae7c8b2017-03-28 19:43:01 +05301574:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
Georg Brandl116aa622007-08-15 14:28:22 +00001575integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001576raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001577if :keyword:`in` raised that exception).
1578
1579.. index::
1580 operator: in
1581 operator: not in
1582 pair: membership; test
1583 object: sequence
1584
1585The operator :keyword:`not in` is defined to have the inverse true value of
1586:keyword:`in`.
1587
1588.. index::
1589 operator: is
1590 operator: is not
1591 pair: identity; test
1592
Martin Panteraa0da862015-09-23 05:28:13 +00001593
1594.. _is:
1595.. _is not:
1596
1597Identity comparisons
1598--------------------
1599
Georg Brandl116aa622007-08-15 14:28:22 +00001600The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
Raymond Hettinger06e18a72016-09-11 17:23:49 -07001601is y`` is true if and only if *x* and *y* are the same object. Object identity
1602is determined using the :meth:`id` function. ``x is not y`` yields the inverse
1603truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001604
1605
1606.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001607.. _and:
1608.. _or:
1609.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001610
1611Boolean operations
1612==================
1613
1614.. index::
1615 pair: Conditional; expression
1616 pair: Boolean; operation
1617
Georg Brandl116aa622007-08-15 14:28:22 +00001618.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001619 or_test: `and_test` | `or_test` "or" `and_test`
1620 and_test: `not_test` | `and_test` "and" `not_test`
1621 not_test: `comparison` | "not" `not_test`
1622
1623In the context of Boolean operations, and also when expressions are used by
1624control flow statements, the following values are interpreted as false:
1625``False``, ``None``, numeric zero of all types, and empty strings and containers
1626(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001627other values are interpreted as true. User-defined objects can customize their
1628truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001629
1630.. index:: operator: not
1631
1632The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1633otherwise.
1634
Georg Brandl116aa622007-08-15 14:28:22 +00001635.. index:: operator: and
1636
1637The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1638returned; otherwise, *y* is evaluated and the resulting value is returned.
1639
1640.. index:: operator: or
1641
1642The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1643returned; otherwise, *y* is evaluated and the resulting value is returned.
1644
1645(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1646they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001647argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001648replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001649the desired value. Because :keyword:`not` has to create a new value, it
1650returns a boolean value regardless of the type of its argument
1651(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001652
1653
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001654Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001655=======================
1656
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001657.. index::
1658 pair: conditional; expression
1659 pair: ternary; operator
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001660 single: if; conditional expression
1661 single: else; conditional expression
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001662
1663.. productionlist::
1664 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001665 expression: `conditional_expression` | `lambda_expr`
1666 expression_nocond: `or_test` | `lambda_expr_nocond`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001667
1668Conditional expressions (sometimes called a "ternary operator") have the lowest
1669priority of all Python operations.
1670
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001671The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1672If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001673evaluated and its value is returned.
1674
1675See :pep:`308` for more details about conditional expressions.
1676
1677
Georg Brandl116aa622007-08-15 14:28:22 +00001678.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001679.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001680
1681Lambdas
1682=======
1683
1684.. index::
1685 pair: lambda; expression
1686 pair: lambda; form
1687 pair: anonymous; function
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001688 single: :; lambda expression
Georg Brandl116aa622007-08-15 14:28:22 +00001689
1690.. productionlist::
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001691 lambda_expr: "lambda" [`parameter_list`] ":" `expression`
1692 lambda_expr_nocond: "lambda" [`parameter_list`] ":" `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001693
Zachary Ware2f78b842014-06-03 09:32:40 -05001694Lambda expressions (sometimes called lambda forms) are used to create anonymous
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001695functions. The expression ``lambda parameters: expression`` yields a function
Martin Panter1050d2d2016-07-26 11:18:21 +02001696object. The unnamed object behaves like a function object defined with:
1697
1698.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +00001699
Andrés Delfino268cc7c2018-05-22 02:57:45 -03001700 def <lambda>(parameters):
Georg Brandl116aa622007-08-15 14:28:22 +00001701 return expression
1702
1703See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001704functions created with lambda expressions cannot contain statements or
1705annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001706
Georg Brandl116aa622007-08-15 14:28:22 +00001707
1708.. _exprlists:
1709
1710Expression lists
1711================
1712
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001713.. index::
1714 pair: expression; list
1715 single: comma; expression list
1716 single: ,; expression list
Georg Brandl116aa622007-08-15 14:28:22 +00001717
1718.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -03001719 expression_list: `expression` ("," `expression`)* [","]
1720 starred_list: `starred_item` ("," `starred_item`)* [","]
1721 starred_expression: `expression` | (`starred_item` ",")* [`starred_item`]
Martin Panter0c0da482016-06-12 01:46:50 +00001722 starred_item: `expression` | "*" `or_expr`
Georg Brandl116aa622007-08-15 14:28:22 +00001723
1724.. index:: object: tuple
1725
Martin Panter0c0da482016-06-12 01:46:50 +00001726Except when part of a list or set display, an expression list
1727containing at least one comma yields a tuple. The length of
Georg Brandl116aa622007-08-15 14:28:22 +00001728the tuple is the number of expressions in the list. The expressions are
1729evaluated from left to right.
1730
Martin Panter0c0da482016-06-12 01:46:50 +00001731.. index::
1732 pair: iterable; unpacking
1733 single: *; in expression lists
1734
1735An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be
1736an :term:`iterable`. The iterable is expanded into a sequence of items,
1737which are included in the new tuple, list, or set, at the site of
1738the unpacking.
1739
1740.. versionadded:: 3.5
1741 Iterable unpacking in expression lists, originally proposed by :pep:`448`.
1742
Georg Brandl116aa622007-08-15 14:28:22 +00001743.. index:: pair: trailing; comma
1744
1745The trailing comma is required only to create a single tuple (a.k.a. a
1746*singleton*); it is optional in all other cases. A single expression without a
1747trailing comma doesn't create a tuple, but rather yields the value of that
1748expression. (To create an empty tuple, use an empty pair of parentheses:
1749``()``.)
1750
1751
1752.. _evalorder:
1753
1754Evaluation order
1755================
1756
1757.. index:: pair: evaluation; order
1758
Georg Brandl96593ed2007-09-07 14:15:41 +00001759Python evaluates expressions from left to right. Notice that while evaluating
1760an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001761
1762In the following lines, expressions will be evaluated in the arithmetic order of
1763their suffixes::
1764
1765 expr1, expr2, expr3, expr4
1766 (expr1, expr2, expr3, expr4)
1767 {expr1: expr2, expr3: expr4}
1768 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001769 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001770 expr3, expr4 = expr1, expr2
1771
1772
1773.. _operator-summary:
1774
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001775Operator precedence
1776===================
Georg Brandl116aa622007-08-15 14:28:22 +00001777
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001778.. index::
1779 pair: operator; precedence
Georg Brandl116aa622007-08-15 14:28:22 +00001780
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001781The following table summarizes the operator precedence in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001782precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001783the same box have the same precedence. Unless the syntax is explicitly given,
1784operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001785exponentiation, which groups from right to left).
1786
1787Note that comparisons, membership tests, and identity tests, all have the same
1788precedence and have a left-to-right chaining feature as described in the
1789:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001790
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001791
1792+-----------------------------------------------+-------------------------------------+
1793| Operator | Description |
1794+===============================================+=====================================+
1795| :keyword:`lambda` | Lambda expression |
1796+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001797| :keyword:`if` -- :keyword:`else` | Conditional expression |
1798+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001799| :keyword:`or` | Boolean OR |
1800+-----------------------------------------------+-------------------------------------+
1801| :keyword:`and` | Boolean AND |
1802+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001803| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001804+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001805| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001806| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001807| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001808+-----------------------------------------------+-------------------------------------+
1809| ``|`` | Bitwise OR |
1810+-----------------------------------------------+-------------------------------------+
1811| ``^`` | Bitwise XOR |
1812+-----------------------------------------------+-------------------------------------+
1813| ``&`` | Bitwise AND |
1814+-----------------------------------------------+-------------------------------------+
1815| ``<<``, ``>>`` | Shifts |
1816+-----------------------------------------------+-------------------------------------+
1817| ``+``, ``-`` | Addition and subtraction |
1818+-----------------------------------------------+-------------------------------------+
Benjamin Petersond51374e2014-04-09 23:55:56 -04001819| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
svelankar9b47af62017-09-17 20:56:16 -04001820| | multiplication, division, floor |
1821| | division, remainder [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001822+-----------------------------------------------+-------------------------------------+
1823| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1824+-----------------------------------------------+-------------------------------------+
1825| ``**`` | Exponentiation [#]_ |
1826+-----------------------------------------------+-------------------------------------+
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001827| :keyword:`await` ``x`` | Await expression |
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001828+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001829| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1830| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1831+-----------------------------------------------+-------------------------------------+
1832| ``(expressions...)``, | Binding or tuple display, |
1833| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001834| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001835| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001836+-----------------------------------------------+-------------------------------------+
1837
Georg Brandl116aa622007-08-15 14:28:22 +00001838
1839.. rubric:: Footnotes
1840
Georg Brandl116aa622007-08-15 14:28:22 +00001841.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1842 true numerically due to roundoff. For example, and assuming a platform on which
1843 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1844 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001845 1e100``, which is numerically exactly equal to ``1e100``. The function
1846 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001847 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1848 is more appropriate depends on the application.
1849
1850.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001851 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001852 cases, Python returns the latter result, in order to preserve that
1853 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1854
Martin Panteraa0da862015-09-23 05:28:13 +00001855.. [#] The Unicode standard distinguishes between :dfn:`code points`
1856 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
1857 While most abstract characters in Unicode are only represented using one
1858 code point, there is a number of abstract characters that can in addition be
1859 represented using a sequence of more than one code point. For example, the
1860 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
1861 as a single :dfn:`precomposed character` at code position U+00C7, or as a
1862 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
1863 LETTER C), followed by a :dfn:`combining character` at code position U+0327
1864 (COMBINING CEDILLA).
1865
1866 The comparison operators on strings compare at the level of Unicode code
1867 points. This may be counter-intuitive to humans. For example,
1868 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1869 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".
1870
1871 To compare strings at the level of abstract characters (that is, in a way
1872 intuitive to humans), use :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001873
Georg Brandl48310cd2009-01-03 21:18:54 +00001874.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001875 descriptors, you may notice seemingly unusual behaviour in certain uses of
1876 the :keyword:`is` operator, like those involving comparisons between instance
1877 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001878
Georg Brandl063f2372010-12-01 15:32:43 +00001879.. [#] The ``%`` operator is also used for string formatting; the same
1880 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001881
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001882.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1883 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.