blob: 99fa037bf6e4748f46021c5883f91f3f48584b42 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2.. _expressions:
3
4***********
5Expressions
6***********
7
Georg Brandl4b491312007-08-31 09:22:56 +00008.. index:: expression, BNF
Georg Brandl116aa622007-08-15 14:28:22 +00009
Brett Cannon7603fa02011-01-06 23:08:16 +000010This chapter explains the meaning of the elements of expressions in Python.
Georg Brandl116aa622007-08-15 14:28:22 +000011
Georg Brandl116aa622007-08-15 14:28:22 +000012**Syntax Notes:** In this and the following chapters, extended BNF notation will
13be used to describe syntax, not lexical analysis. When (one alternative of) a
14syntax rule has the form
15
16.. productionlist:: *
17 name: `othername`
18
Georg Brandl116aa622007-08-15 14:28:22 +000019and no semantics are given, the semantics of this form of ``name`` are the same
20as for ``othername``.
21
22
23.. _conversions:
24
25Arithmetic conversions
26======================
27
28.. index:: pair: arithmetic; conversion
29
Georg Brandl116aa622007-08-15 14:28:22 +000030When a description of an arithmetic operator below uses the phrase "the numeric
Georg Brandl96593ed2007-09-07 14:15:41 +000031arguments are converted to a common type," this means that the operator
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070032implementation for built-in types works as follows:
Georg Brandl116aa622007-08-15 14:28:22 +000033
34* If either argument is a complex number, the other is converted to complex;
35
36* otherwise, if either argument is a floating point number, the other is
37 converted to floating point;
38
Georg Brandl96593ed2007-09-07 14:15:41 +000039* otherwise, both must be integers and no conversion is necessary.
Georg Brandl116aa622007-08-15 14:28:22 +000040
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070041Some additional rules apply for certain operators (e.g., a string as a left
42argument to the '%' operator). Extensions must define their own conversion
43behavior.
Georg Brandl116aa622007-08-15 14:28:22 +000044
45
46.. _atoms:
47
48Atoms
49=====
50
Georg Brandl96593ed2007-09-07 14:15:41 +000051.. index:: atom
Georg Brandl116aa622007-08-15 14:28:22 +000052
53Atoms are the most basic elements of expressions. The simplest atoms are
Georg Brandl96593ed2007-09-07 14:15:41 +000054identifiers or literals. Forms enclosed in parentheses, brackets or braces are
55also categorized syntactically as atoms. The syntax for atoms is:
Georg Brandl116aa622007-08-15 14:28:22 +000056
57.. productionlist::
58 atom: `identifier` | `literal` | `enclosure`
Georg Brandl96593ed2007-09-07 14:15:41 +000059 enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display`
60 : | `generator_expression` | `yield_atom`
Georg Brandl116aa622007-08-15 14:28:22 +000061
62
63.. _atom-identifiers:
64
65Identifiers (Names)
66-------------------
67
Georg Brandl96593ed2007-09-07 14:15:41 +000068.. index:: name, identifier
Georg Brandl116aa622007-08-15 14:28:22 +000069
70An identifier occurring as an atom is a name. See section :ref:`identifiers`
71for lexical definition and section :ref:`naming` for documentation of naming and
72binding.
73
74.. index:: exception: NameError
75
76When the name is bound to an object, evaluation of the atom yields that object.
77When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
78exception.
79
80.. index::
81 pair: name; mangling
82 pair: private; names
83
84**Private name mangling:** When an identifier that textually occurs in a class
85definition begins with two or more underscore characters and does not end in two
86or more underscores, it is considered a :dfn:`private name` of that class.
87Private names are transformed to a longer form before code is generated for
Georg Brandldec3b3f2013-04-14 10:13:42 +020088them. The transformation inserts the class name, with leading underscores
89removed and a single underscore inserted, in front of the name. For example,
90the identifier ``__spam`` occurring in a class named ``Ham`` will be transformed
91to ``_Ham__spam``. This transformation is independent of the syntactical
92context in which the identifier is used. If the transformed name is extremely
93long (longer than 255 characters), implementation defined truncation may happen.
94If the class name consists only of underscores, no transformation is done.
Georg Brandl116aa622007-08-15 14:28:22 +000095
Georg Brandl116aa622007-08-15 14:28:22 +000096
97.. _atom-literals:
98
99Literals
100--------
101
102.. index:: single: literal
103
Georg Brandl96593ed2007-09-07 14:15:41 +0000104Python supports string and bytes literals and various numeric literals:
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000107 literal: `stringliteral` | `bytesliteral`
108 : | `integer` | `floatnumber` | `imagnumber`
Georg Brandl116aa622007-08-15 14:28:22 +0000109
Georg Brandl96593ed2007-09-07 14:15:41 +0000110Evaluation of a literal yields an object of the given type (string, bytes,
111integer, floating point number, complex number) with the given value. The value
112may be approximated in the case of floating point and imaginary (complex)
Georg Brandl116aa622007-08-15 14:28:22 +0000113literals. See section :ref:`literals` for details.
114
115.. index::
116 triple: immutable; data; type
117 pair: immutable; object
118
Terry Jan Reedyead1de22012-02-17 19:56:58 -0500119All literals correspond to immutable data types, and hence the object's identity
120is less important than its value. Multiple evaluations of literals with the
121same value (either the same occurrence in the program text or a different
122occurrence) may obtain the same object or a different object with the same
123value.
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125
126.. _parenthesized:
127
128Parenthesized forms
129-------------------
130
131.. index:: single: parenthesized form
132
133A parenthesized form is an optional expression list enclosed in parentheses:
134
135.. productionlist::
136 parenth_form: "(" [`expression_list`] ")"
137
138A parenthesized expression list yields whatever that expression list yields: if
139the list contains at least one comma, it yields a tuple; otherwise, it yields
140the single expression that makes up the expression list.
141
142.. index:: pair: empty; tuple
143
144An empty pair of parentheses yields an empty tuple object. Since tuples are
145immutable, the rules for literals apply (i.e., two occurrences of the empty
146tuple may or may not yield the same object).
147
148.. index::
149 single: comma
150 pair: tuple; display
151
152Note that tuples are not formed by the parentheses, but rather by use of the
153comma operator. The exception is the empty tuple, for which parentheses *are*
154required --- allowing unparenthesized "nothing" in expressions would cause
155ambiguities and allow common typos to pass uncaught.
156
157
Georg Brandl96593ed2007-09-07 14:15:41 +0000158.. _comprehensions:
159
160Displays for lists, sets and dictionaries
161-----------------------------------------
162
163For constructing a list, a set or a dictionary Python provides special syntax
164called "displays", each of them in two flavors:
165
166* either the container contents are listed explicitly, or
167
168* they are computed via a set of looping and filtering instructions, called a
169 :dfn:`comprehension`.
170
171Common syntax elements for comprehensions are:
172
173.. productionlist::
174 comprehension: `expression` `comp_for`
175 comp_for: "for" `target_list` "in" `or_test` [`comp_iter`]
176 comp_iter: `comp_for` | `comp_if`
177 comp_if: "if" `expression_nocond` [`comp_iter`]
178
179The comprehension consists of a single expression followed by at least one
180:keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` clauses.
181In this case, the elements of the new container are those that would be produced
182by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
183nesting from left to right, and evaluating the expression to produce an element
184each time the innermost block is reached.
185
Georg Brandl02c30562007-09-07 17:52:53 +0000186Note that the comprehension is executed in a separate scope, so names assigned
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700187to in the target list don't "leak" into the enclosing scope.
Georg Brandl02c30562007-09-07 17:52:53 +0000188
Georg Brandl96593ed2007-09-07 14:15:41 +0000189
Georg Brandl116aa622007-08-15 14:28:22 +0000190.. _lists:
191
192List displays
193-------------
194
195.. index::
196 pair: list; display
197 pair: list; comprehensions
Georg Brandl96593ed2007-09-07 14:15:41 +0000198 pair: empty; list
199 object: list
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201A list display is a possibly empty series of expressions enclosed in square
202brackets:
203
204.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000205 list_display: "[" [`expression_list` | `comprehension`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000206
Georg Brandl96593ed2007-09-07 14:15:41 +0000207A list display yields a new list object, the contents being specified by either
208a list of expressions or a comprehension. When a comma-separated list of
209expressions is supplied, its elements are evaluated from left to right and
210placed into the list object in that order. When a comprehension is supplied,
211the list is constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000212
213
Georg Brandl96593ed2007-09-07 14:15:41 +0000214.. _set:
Georg Brandl116aa622007-08-15 14:28:22 +0000215
Georg Brandl96593ed2007-09-07 14:15:41 +0000216Set displays
217------------
Georg Brandl116aa622007-08-15 14:28:22 +0000218
Georg Brandl96593ed2007-09-07 14:15:41 +0000219.. index:: pair: set; display
220 object: set
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Georg Brandl96593ed2007-09-07 14:15:41 +0000222A set display is denoted by curly braces and distinguishable from dictionary
223displays by the lack of colons separating keys and values:
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225.. productionlist::
Georg Brandl528cdb12008-09-21 07:09:51 +0000226 set_display: "{" (`expression_list` | `comprehension`) "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000227
Georg Brandl96593ed2007-09-07 14:15:41 +0000228A set display yields a new mutable set object, the contents being specified by
229either a sequence of expressions or a comprehension. When a comma-separated
230list of expressions is supplied, its elements are evaluated from left to right
231and added to the set object. When a comprehension is supplied, the set is
232constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000233
Georg Brandl528cdb12008-09-21 07:09:51 +0000234An empty set cannot be constructed with ``{}``; this literal constructs an empty
235dictionary.
Christian Heimes78644762008-03-04 23:39:23 +0000236
237
Georg Brandl116aa622007-08-15 14:28:22 +0000238.. _dict:
239
240Dictionary displays
241-------------------
242
243.. index:: pair: dictionary; display
Georg Brandl96593ed2007-09-07 14:15:41 +0000244 key, datum, key/datum pair
245 object: dictionary
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247A dictionary display is a possibly empty series of key/datum pairs enclosed in
248curly braces:
249
250.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000251 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000252 key_datum_list: `key_datum` ("," `key_datum`)* [","]
253 key_datum: `expression` ":" `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +0000254 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256A dictionary display yields a new dictionary object.
257
Georg Brandl96593ed2007-09-07 14:15:41 +0000258If a comma-separated sequence of key/datum pairs is given, they are evaluated
259from left to right to define the entries of the dictionary: each key object is
260used as a key into the dictionary to store the corresponding datum. This means
261that you can specify the same key multiple times in the key/datum list, and the
262final dictionary's value for that key will be the last one given.
263
264A dict comprehension, in contrast to list and set comprehensions, needs two
265expressions separated with a colon followed by the usual "for" and "if" clauses.
266When the comprehension is run, the resulting key and value elements are inserted
267in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000268
269.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000270 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000273:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000274all mutable objects.) Clashes between duplicate keys are not detected; the last
275datum (textually rightmost in the display) stored for a given key value
276prevails.
277
278
Georg Brandl96593ed2007-09-07 14:15:41 +0000279.. _genexpr:
280
281Generator expressions
282---------------------
283
284.. index:: pair: generator; expression
285 object: generator
286
287A generator expression is a compact generator notation in parentheses:
288
289.. productionlist::
290 generator_expression: "(" `expression` `comp_for` ")"
291
292A generator expression yields a new generator object. Its syntax is the same as
293for comprehensions, except that it is enclosed in parentheses instead of
294brackets or curly braces.
295
296Variables used in the generator expression are evaluated lazily when the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700297:meth:`~generator.__next__` method is called for the generator object (in the same
Ezio Melotti7fa82222012-10-12 13:42:08 +0300298fashion as normal generators). However, the leftmost :keyword:`for` clause is
299immediately evaluated, so that an error produced by it can be seen before any
300other possible error in the code that handles the generator expression.
301Subsequent :keyword:`for` clauses cannot be evaluated immediately since they
302may depend on the previous :keyword:`for` loop. For example: ``(x*y for x in
303range(10) for y in bar(x))``.
Georg Brandl96593ed2007-09-07 14:15:41 +0000304
305The parentheses can be omitted on calls with only one argument. See section
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700306:ref:`calls` for details.
Georg Brandl96593ed2007-09-07 14:15:41 +0000307
308
Georg Brandl116aa622007-08-15 14:28:22 +0000309.. _yieldexpr:
310
311Yield expressions
312-----------------
313
314.. index::
315 keyword: yield
316 pair: yield; expression
317 pair: generator; function
318
319.. productionlist::
320 yield_atom: "(" `yield_expression` ")"
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000321 yield_expression: "yield" [`expression_list` | "from" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000322
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500323The yield expression is only used when defining a :term:`generator` function and
324thus can only be used in the body of a function definition. Using a yield
325expression in a function's body causes that function to be a generator.
Georg Brandl116aa622007-08-15 14:28:22 +0000326
327When a generator function is called, it returns an iterator known as a
Guido van Rossumd0150ad2015-05-05 12:02:01 -0700328generator. That generator then controls the execution of the generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000329The execution starts when one of the generator's methods is called. At that
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500330time, the execution proceeds to the first yield expression, where it is
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700331suspended again, returning the value of :token:`expression_list` to the generator's
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500332caller. By suspended, we mean that all local state is retained, including the
Ethan Furman2f825af2015-01-14 22:25:27 -0800333current bindings of local variables, the instruction pointer, the internal
334evaluation stack, and the state of any exception handling. When the execution
335is resumed by calling one of the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500336generator's methods, the function can proceed exactly as if the yield expression
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700337were just another external call. The value of the yield expression after
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500338resuming depends on the method which resumed the execution. If
339:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or
340the :func:`next` builtin) then the result is :const:`None`. Otherwise, if
341:meth:`~generator.send` is used, then the result will be the value passed in to
342that method.
Georg Brandl116aa622007-08-15 14:28:22 +0000343
344.. index:: single: coroutine
345
346All of this makes generator functions quite similar to coroutines; they yield
347multiple times, they have more than one entry point and their execution can be
348suspended. The only difference is that a generator function cannot control
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700349where the execution should continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000350transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000351
Ethan Furman2f825af2015-01-14 22:25:27 -0800352Yield expressions are allowed anywhere in a :keyword:`try` construct. If the
353generator is not resumed before it is
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500354finalized (by reaching a zero reference count or by being garbage collected),
355the generator-iterator's :meth:`~generator.close` method will be called,
356allowing any pending :keyword:`finally` clauses to execute.
Georg Brandl02c30562007-09-07 17:52:53 +0000357
Nick Coghlan0ed80192012-01-14 14:43:24 +1000358When ``yield from <expr>`` is used, it treats the supplied expression as
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000359a subiterator. All values produced by that subiterator are passed directly
360to the caller of the current generator's methods. Any values passed in with
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300361:meth:`~generator.send` and any exceptions passed in with
362:meth:`~generator.throw` are passed to the underlying iterator if it has the
363appropriate methods. If this is not the case, then :meth:`~generator.send`
364will raise :exc:`AttributeError` or :exc:`TypeError`, while
365:meth:`~generator.throw` will just raise the passed in exception immediately.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000366
367When the underlying iterator is complete, the :attr:`~StopIteration.value`
368attribute of the raised :exc:`StopIteration` instance becomes the value of
369the yield expression. It can be either set explicitly when raising
370:exc:`StopIteration`, or automatically when the sub-iterator is a generator
371(by returning a value from the sub-generator).
372
Nick Coghlan0ed80192012-01-14 14:43:24 +1000373 .. versionchanged:: 3.3
Martin Panterd21e0b52015-10-10 10:36:22 +0000374 Added ``yield from <expr>`` to delegate control flow to a subiterator.
Nick Coghlan0ed80192012-01-14 14:43:24 +1000375
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500376The parentheses may be omitted when the yield expression is the sole expression
377on the right hand side of an assignment statement.
378
379.. seealso::
380
381 :pep:`0255` - Simple Generators
382 The proposal for adding generators and the :keyword:`yield` statement to Python.
383
384 :pep:`0342` - Coroutines via Enhanced Generators
385 The proposal to enhance the API and syntax of generators, making them
386 usable as simple coroutines.
387
388 :pep:`0380` - Syntax for Delegating to a Subgenerator
389 The proposal to introduce the :token:`yield_from` syntax, making delegation
390 to sub-generators easy.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000391
Georg Brandl116aa622007-08-15 14:28:22 +0000392.. index:: object: generator
Yury Selivanov66f88282015-06-24 11:04:15 -0400393.. _generator-methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000394
R David Murray2c1d1d62012-08-17 20:48:59 -0400395Generator-iterator methods
396^^^^^^^^^^^^^^^^^^^^^^^^^^
397
398This subsection describes the methods of a generator iterator. They can
399be used to control the execution of a generator function.
400
401Note that calling any of the generator methods below when the generator
402is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404.. index:: exception: StopIteration
405
406
Georg Brandl96593ed2007-09-07 14:15:41 +0000407.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Georg Brandl96593ed2007-09-07 14:15:41 +0000409 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500410 executed yield expression. When a generator function is resumed with a
411 :meth:`~generator.__next__` method, the current yield expression always
412 evaluates to :const:`None`. The execution then continues to the next yield
413 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300414 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500415 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000416 exception is raised.
417
418 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
419 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421
422.. method:: generator.send(value)
423
424 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500425 *value* argument becomes the result of the current yield expression. The
426 :meth:`send` method returns the next value yielded by the generator, or
427 raises :exc:`StopIteration` if the generator exits without yielding another
428 value. When :meth:`send` is called to start the generator, it must be called
429 with :const:`None` as the argument, because there is no yield expression that
430 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000431
432
433.. method:: generator.throw(type[, value[, traceback]])
434
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700435 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000436 and returns the next value yielded by the generator function. If the generator
437 exits without yielding another value, a :exc:`StopIteration` exception is
438 raised. If the generator function does not catch the passed-in exception, or
439 raises a different exception, then that exception propagates to the caller.
440
441.. index:: exception: GeneratorExit
442
443
444.. method:: generator.close()
445
446 Raises a :exc:`GeneratorExit` at the point where the generator function was
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400447 paused. If the generator function then exits gracefully, is already closed,
448 or raises :exc:`GeneratorExit` (by not catching the exception), close
449 returns to its caller. If the generator yields a value, a
450 :exc:`RuntimeError` is raised. If the generator raises any other exception,
451 it is propagated to the caller. :meth:`close` does nothing if the generator
452 has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000453
Chris Jerdonek2654b862012-12-23 15:31:57 -0800454.. index:: single: yield; examples
455
456Examples
457^^^^^^^^
458
Georg Brandl116aa622007-08-15 14:28:22 +0000459Here is a simple example that demonstrates the behavior of generators and
460generator functions::
461
462 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000463 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000464 ... try:
465 ... while True:
466 ... try:
467 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000468 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000469 ... value = e
470 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000471 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000472 ...
473 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000474 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000475 Execution starts when 'next()' is called for the first time.
476 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000477 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000478 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000479 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000480 2
481 >>> generator.throw(TypeError, "spam")
482 TypeError('spam',)
483 >>> generator.close()
484 Don't forget to clean up when 'close()' is called.
485
Chris Jerdonek2654b862012-12-23 15:31:57 -0800486For examples using ``yield from``, see :ref:`pep-380` in "What's New in
487Python."
488
Georg Brandl116aa622007-08-15 14:28:22 +0000489
Georg Brandl116aa622007-08-15 14:28:22 +0000490.. _primaries:
491
492Primaries
493=========
494
495.. index:: single: primary
496
497Primaries represent the most tightly bound operations of the language. Their
498syntax is:
499
500.. productionlist::
501 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
502
503
504.. _attribute-references:
505
506Attribute references
507--------------------
508
509.. index:: pair: attribute; reference
510
511An attribute reference is a primary followed by a period and a name:
512
513.. productionlist::
514 attributeref: `primary` "." `identifier`
515
516.. index::
517 exception: AttributeError
518 object: module
519 object: list
520
521The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000522references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700523attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500524overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700525the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
526the object produced is determined by the object. Multiple evaluations of the
527same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529
530.. _subscriptions:
531
532Subscriptions
533-------------
534
535.. index:: single: subscription
536
537.. index::
538 object: sequence
539 object: mapping
540 object: string
541 object: tuple
542 object: list
543 object: dictionary
544 pair: sequence; item
545
546A subscription selects an item of a sequence (string, tuple or list) or mapping
547(dictionary) object:
548
549.. productionlist::
550 subscription: `primary` "[" `expression_list` "]"
551
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700552The primary must evaluate to an object that supports subscription (lists or
553dictionaries for example). User-defined objects can support subscription by
554defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000555
556For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000557
558If the primary is a mapping, the expression list must evaluate to an object
559whose value is one of the keys of the mapping, and the subscription selects the
560value in the mapping that corresponds to that key. (The expression list is a
561tuple except if it has exactly one item.)
562
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000563If the primary is a sequence, the expression (list) must evaluate to an integer
564or a slice (as discussed in the following section).
565
566The formal syntax makes no special provision for negative indices in
567sequences; however, built-in sequences all provide a :meth:`__getitem__`
568method that interprets negative indices by adding the length of the sequence
569to the index (so that ``x[-1]`` selects the last item of ``x``). The
570resulting value must be a nonnegative integer less than the number of items in
571the sequence, and the subscription selects the item whose index is that value
572(counting from zero). Since the support for negative indices and slicing
573occurs in the object's :meth:`__getitem__` method, subclasses overriding
574this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000575
576.. index::
577 single: character
578 pair: string; item
579
580A string's items are characters. A character is not a separate data type but a
581string of exactly one character.
582
583
584.. _slicings:
585
586Slicings
587--------
588
589.. index::
590 single: slicing
591 single: slice
592
593.. index::
594 object: sequence
595 object: string
596 object: tuple
597 object: list
598
599A slicing selects a range of items in a sequence object (e.g., a string, tuple
600or list). Slicings may be used as expressions or as targets in assignment or
601:keyword:`del` statements. The syntax for a slicing:
602
603.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000604 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000605 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000606 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000607 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000608 lower_bound: `expression`
609 upper_bound: `expression`
610 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000611
612There is ambiguity in the formal syntax here: anything that looks like an
613expression list also looks like a slice list, so any subscription can be
614interpreted as a slicing. Rather than further complicating the syntax, this is
615disambiguated by defining that in this case the interpretation as a subscription
616takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000617slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000618
619.. index::
620 single: start (slice object attribute)
621 single: stop (slice object attribute)
622 single: step (slice object attribute)
623
Georg Brandla4c8c472014-10-31 10:38:49 +0100624The semantics for a slicing are as follows. The primary is indexed (using the
625same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000626normal subscription) with a key that is constructed from the slice list, as
627follows. If the slice list contains at least one comma, the key is a tuple
628containing the conversion of the slice items; otherwise, the conversion of the
629lone slice item is the key. The conversion of a slice item that is an
630expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300631object (see section :ref:`types`) whose :attr:`~slice.start`,
632:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
633expressions given as lower bound, upper bound and stride, respectively,
634substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000635
636
Chris Jerdonekb4309942012-12-25 14:54:44 -0800637.. index::
638 object: callable
639 single: call
640 single: argument; call semantics
641
Georg Brandl116aa622007-08-15 14:28:22 +0000642.. _calls:
643
644Calls
645-----
646
Chris Jerdonekb4309942012-12-25 14:54:44 -0800647A call calls a callable object (e.g., a :term:`function`) with a possibly empty
648series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000649
650.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000651 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000652 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000653 : ["," "*" `expression`] ["," `keyword_arguments`]
654 : ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000655 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000656 : ["," `keyword_arguments`] ["," "**" `expression`]
657 : | "*" `expression` ["," `keyword_arguments`] ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000658 : | "**" `expression`
659 positional_arguments: `expression` ("," `expression`)*
660 keyword_arguments: `keyword_item` ("," `keyword_item`)*
661 keyword_item: `identifier` "=" `expression`
662
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700663An optional trailing comma may be present after the positional and keyword arguments
664but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000665
Chris Jerdonekb4309942012-12-25 14:54:44 -0800666.. index::
667 single: parameter; call semantics
668
Georg Brandl116aa622007-08-15 14:28:22 +0000669The primary must evaluate to a callable object (user-defined functions, built-in
670functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000671instances, and all objects having a :meth:`__call__` method are callable). All
672argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800673to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000674
675.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000676
677If keyword arguments are present, they are first converted to positional
678arguments, as follows. First, a list of unfilled slots is created for the
679formal parameters. If there are N positional arguments, they are placed in the
680first N slots. Next, for each keyword argument, the identifier is used to
681determine the corresponding slot (if the identifier is the same as the first
682formal parameter name, the first slot is used, and so on). If the slot is
683already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
684the argument is placed in the slot, filling it (even if the expression is
685``None``, it fills the slot). When all arguments have been processed, the slots
686that are still unfilled are filled with the corresponding default value from the
687function definition. (Default values are calculated, once, when the function is
688defined; thus, a mutable object such as a list or dictionary used as default
689value will be shared by all calls that don't specify an argument value for the
690corresponding slot; this should usually be avoided.) If there are any unfilled
691slots for which no default value is specified, a :exc:`TypeError` exception is
692raised. Otherwise, the list of filled slots is used as the argument list for
693the call.
694
Georg Brandl495f7b52009-10-27 15:28:25 +0000695.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000696
Georg Brandl495f7b52009-10-27 15:28:25 +0000697 An implementation may provide built-in functions whose positional parameters
698 do not have names, even if they are 'named' for the purpose of documentation,
699 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000700 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000701 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000702
Georg Brandl116aa622007-08-15 14:28:22 +0000703If there are more positional arguments than there are formal parameter slots, a
704:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
705``*identifier`` is present; in this case, that formal parameter receives a tuple
706containing the excess positional arguments (or an empty tuple if there were no
707excess positional arguments).
708
709If any keyword argument does not correspond to a formal parameter name, a
710:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
711``**identifier`` is present; in this case, that formal parameter receives a
712dictionary containing the excess keyword arguments (using the keywords as keys
713and the argument values as corresponding values), or a (new) empty dictionary if
714there were no excess keyword arguments.
715
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300716.. index::
717 single: *; in function calls
718
Georg Brandl116aa622007-08-15 14:28:22 +0000719If the syntax ``*expression`` appears in the function call, ``expression`` must
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300720evaluate to an iterable. Elements from this iterable are treated as if they
721were additional positional arguments; if there are positional arguments
Ezio Melotti59256322011-07-30 21:25:22 +0300722*x1*, ..., *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*,
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300723this is equivalent to a call with M+N positional arguments *x1*, ..., *xN*,
724*y1*, ..., *yM*.
Georg Brandl116aa622007-08-15 14:28:22 +0000725
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000726A consequence of this is that although the ``*expression`` syntax may appear
727*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000728(and the ``**expression`` argument, if any -- see below). So::
729
730 >>> def f(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000731 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000732 ...
733 >>> f(b=1, *(2,))
734 2 1
735 >>> f(a=1, *(2,))
736 Traceback (most recent call last):
737 File "<stdin>", line 1, in ?
738 TypeError: f() got multiple values for keyword argument 'a'
739 >>> f(1, *(2,))
740 1 2
741
742It is unusual for both keyword arguments and the ``*expression`` syntax to be
743used in the same call, so in practice this confusion does not arise.
744
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300745.. index::
746 single: **; in function calls
747
Georg Brandl116aa622007-08-15 14:28:22 +0000748If the syntax ``**expression`` appears in the function call, ``expression`` must
749evaluate to a mapping, the contents of which are treated as additional keyword
750arguments. In the case of a keyword appearing in both ``expression`` and as an
751explicit keyword argument, a :exc:`TypeError` exception is raised.
752
753Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
754used as positional argument slots or as keyword argument names.
755
756A call always returns some value, possibly ``None``, unless it raises an
757exception. How this value is computed depends on the type of the callable
758object.
759
760If it is---
761
762a user-defined function:
763 .. index::
764 pair: function; call
765 triple: user-defined; function; call
766 object: user-defined function
767 object: function
768
769 The code block for the function is executed, passing it the argument list. The
770 first thing the code block will do is bind the formal parameters to the
771 arguments; this is described in section :ref:`function`. When the code block
772 executes a :keyword:`return` statement, this specifies the return value of the
773 function call.
774
775a built-in function or method:
776 .. index::
777 pair: function; call
778 pair: built-in function; call
779 pair: method; call
780 pair: built-in method; call
781 object: built-in method
782 object: built-in function
783 object: method
784 object: function
785
786 The result is up to the interpreter; see :ref:`built-in-funcs` for the
787 descriptions of built-in functions and methods.
788
789a class object:
790 .. index::
791 object: class
792 pair: class object; call
793
794 A new instance of that class is returned.
795
796a class instance method:
797 .. index::
798 object: class instance
799 object: instance
800 pair: class instance; call
801
802 The corresponding user-defined function is called, with an argument list that is
803 one longer than the argument list of the call: the instance becomes the first
804 argument.
805
806a class instance:
807 .. index::
808 pair: instance; call
809 single: __call__() (object method)
810
811 The class must define a :meth:`__call__` method; the effect is then the same as
812 if that method was called.
813
814
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400815.. _await:
816
817Await expression
818================
819
820Suspend the execution of :term:`coroutine` on an :term:`awaitable` object.
821Can only be used inside a :term:`coroutine function`.
822
823.. productionlist::
824 await: ["await"] `primary`
825
826.. versionadded:: 3.5
827
828
Georg Brandl116aa622007-08-15 14:28:22 +0000829.. _power:
830
831The power operator
832==================
833
834The power operator binds more tightly than unary operators on its left; it binds
835less tightly than unary operators on its right. The syntax is:
836
837.. productionlist::
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400838 power: `await` ["**" `u_expr`]
Georg Brandl116aa622007-08-15 14:28:22 +0000839
840Thus, in an unparenthesized sequence of power and unary operators, the operators
841are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +0000842for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000843
844The power operator has the same semantics as the built-in :func:`pow` function,
845when called with two arguments: it yields its left argument raised to the power
846of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +0000847type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +0000848
Georg Brandl96593ed2007-09-07 14:15:41 +0000849For int operands, the result has the same type as the operands unless the second
850argument is negative; in that case, all arguments are converted to float and a
851float result is delivered. For example, ``10**2`` returns ``100``, but
852``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +0000853
854Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +0000855Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +0000856number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000857
858
859.. _unary:
860
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000861Unary arithmetic and bitwise operations
862=======================================
Georg Brandl116aa622007-08-15 14:28:22 +0000863
864.. index::
865 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +0000866 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000867
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000868All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +0000869
870.. productionlist::
871 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
872
873.. index::
874 single: negation
875 single: minus
876
877The unary ``-`` (minus) operator yields the negation of its numeric argument.
878
879.. index:: single: plus
880
881The unary ``+`` (plus) operator yields its numeric argument unchanged.
882
883.. index:: single: inversion
884
Christian Heimesfaf2f632008-01-06 16:59:19 +0000885
Georg Brandl95817b32008-05-11 14:30:18 +0000886The unary ``~`` (invert) operator yields the bitwise inversion of its integer
887argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
888applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000889
890.. index:: exception: TypeError
891
892In all three cases, if the argument does not have the proper type, a
893:exc:`TypeError` exception is raised.
894
895
896.. _binary:
897
898Binary arithmetic operations
899============================
900
901.. index:: triple: binary; arithmetic; operation
902
903The binary arithmetic operations have the conventional priority levels. Note
904that some of these operations also apply to certain non-numeric types. Apart
905from the power operator, there are only two levels, one for multiplicative
906operators and one for additive operators:
907
908.. productionlist::
Benjamin Petersond51374e2014-04-09 23:55:56 -0400909 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
910 : `m_expr` "//" `u_expr`| `m_expr` "/" `u_expr` |
911 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +0000912 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
913
914.. index:: single: multiplication
915
916The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +0000917arguments must either both be numbers, or one argument must be an integer and
918the other must be a sequence. In the former case, the numbers are converted to a
919common type and then multiplied together. In the latter case, sequence
920repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000921
Benjamin Petersond51374e2014-04-09 23:55:56 -0400922.. index:: single: matrix multiplication
923
924The ``@`` (at) operator is intended to be used for matrix multiplication. No
925builtin Python types implement this operator.
926
927.. versionadded:: 3.5
928
Georg Brandl116aa622007-08-15 14:28:22 +0000929.. index::
930 exception: ZeroDivisionError
931 single: division
932
933The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
934their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +0200935Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +0000936integer; the result is that of mathematical division with the 'floor' function
937applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
938exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000939
940.. index:: single: modulo
941
942The ``%`` (modulo) operator yields the remainder from the division of the first
943argument by the second. The numeric arguments are first converted to a common
944type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
945arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
946(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
947result with the same sign as its second operand (or zero); the absolute value of
948the result is strictly smaller than the absolute value of the second operand
949[#]_.
950
Georg Brandl96593ed2007-09-07 14:15:41 +0000951The floor division and modulo operators are connected by the following
952identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
953connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
954x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000955
956In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +0000957also overloaded by string objects to perform old-style string formatting (also
958known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +0000959Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +0000960
961The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +0000962function are not defined for complex numbers. Instead, convert to a floating
963point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +0000964
965.. index:: single: addition
966
Georg Brandl96593ed2007-09-07 14:15:41 +0000967The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700968must either both be numbers or both be sequences of the same type. In the
969former case, the numbers are converted to a common type and then added together.
970In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +0000971
972.. index:: single: subtraction
973
974The ``-`` (subtraction) operator yields the difference of its arguments. The
975numeric arguments are first converted to a common type.
976
977
978.. _shifting:
979
980Shifting operations
981===================
982
983.. index:: pair: shifting; operation
984
985The shifting operations have lower priority than the arithmetic operations:
986
987.. productionlist::
988 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
989
Georg Brandl96593ed2007-09-07 14:15:41 +0000990These operators accept integers as arguments. They shift the first argument to
991the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000992
993.. index:: exception: ValueError
994
Georg Brandl0aaae262013-10-08 21:47:18 +0200995A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
996shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000997
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000998.. note::
999
1000 In the current implementation, the right-hand operand is required
Mark Dickinson505add32010-04-06 18:22:06 +00001001 to be at most :attr:`sys.maxsize`. If the right-hand operand is larger than
1002 :attr:`sys.maxsize` an :exc:`OverflowError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001003
1004.. _bitwise:
1005
Christian Heimesfaf2f632008-01-06 16:59:19 +00001006Binary bitwise operations
1007=========================
Georg Brandl116aa622007-08-15 14:28:22 +00001008
Christian Heimesfaf2f632008-01-06 16:59:19 +00001009.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +00001010
1011Each of the three bitwise operations has a different priority level:
1012
1013.. productionlist::
1014 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1015 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1016 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1017
Christian Heimesfaf2f632008-01-06 16:59:19 +00001018.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +00001019
Georg Brandl96593ed2007-09-07 14:15:41 +00001020The ``&`` operator yields the bitwise AND of its arguments, which must be
1021integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001022
1023.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001024 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001025 pair: exclusive; or
1026
1027The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001028must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001029
1030.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001031 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001032 pair: inclusive; or
1033
1034The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001035must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001036
1037
1038.. _comparisons:
1039
1040Comparisons
1041===========
1042
1043.. index:: single: comparison
1044
1045.. index:: pair: C; language
1046
1047Unlike C, all comparison operations in Python have the same priority, which is
1048lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1049C, expressions like ``a < b < c`` have the interpretation that is conventional
1050in mathematics:
1051
1052.. productionlist::
1053 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1054 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1055 : | "is" ["not"] | ["not"] "in"
1056
1057Comparisons yield boolean values: ``True`` or ``False``.
1058
1059.. index:: pair: chaining; comparisons
1060
1061Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1062``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1063cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1064
Guido van Rossum04110fb2007-08-24 16:32:05 +00001065Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1066*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1067to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1068evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001069
Guido van Rossum04110fb2007-08-24 16:32:05 +00001070Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001071*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1072pretty).
1073
Martin Panteraa0da862015-09-23 05:28:13 +00001074Value comparisons
1075-----------------
1076
Georg Brandl116aa622007-08-15 14:28:22 +00001077The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
Martin Panteraa0da862015-09-23 05:28:13 +00001078values of two objects. The objects do not need to have the same type.
Georg Brandl116aa622007-08-15 14:28:22 +00001079
Martin Panteraa0da862015-09-23 05:28:13 +00001080Chapter :ref:`objects` states that objects have a value (in addition to type
1081and identity). The value of an object is a rather abstract notion in Python:
1082For example, there is no canonical access method for an object's value. Also,
1083there is no requirement that the value of an object should be constructed in a
1084particular way, e.g. comprised of all its data attributes. Comparison operators
1085implement a particular notion of what the value of an object is. One can think
1086of them as defining the value of an object indirectly, by means of their
1087comparison implementation.
Georg Brandl116aa622007-08-15 14:28:22 +00001088
Martin Panteraa0da862015-09-23 05:28:13 +00001089Because all types are (direct or indirect) subtypes of :class:`object`, they
1090inherit the default comparison behavior from :class:`object`. Types can
1091customize their comparison behavior by implementing
1092:dfn:`rich comparison methods` like :meth:`__lt__`, described in
1093:ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001094
Martin Panteraa0da862015-09-23 05:28:13 +00001095The default behavior for equality comparison (``==`` and ``!=``) is based on
1096the identity of the objects. Hence, equality comparison of instances with the
1097same identity results in equality, and equality comparison of instances with
1098different identities results in inequality. A motivation for this default
1099behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1100implies ``x == y``).
1101
1102A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1103an attempt raises :exc:`TypeError`. A motivation for this default behavior is
1104the lack of a similar invariant as for equality.
1105
1106The behavior of the default equality comparison, that instances with different
1107identities are always unequal, may be in contrast to what types will need that
1108have a sensible definition of object value and value-based equality. Such
1109types will need to customize their comparison behavior, and in fact, a number
1110of built-in types have done that.
1111
1112The following list describes the comparison behavior of the most important
1113built-in types.
1114
1115* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1116 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
1117 compared within and across their types, with the restriction that complex
1118 numbers do not support order comparison. Within the limits of the types
1119 involved, they compare mathematically (algorithmically) correct without loss
1120 of precision.
1121
1122 The not-a-number values :const:`float('NaN')` and :const:`Decimal('NaN')`
1123 are special. They are identical to themselves (``x is x`` is true) but
1124 are not equal to themselves (``x == x`` is false). Additionally,
1125 comparing any number to a not-a-number value
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001126 will return ``False``. For example, both ``3 < float('NaN')`` and
1127 ``float('NaN') < 3`` will return ``False``.
1128
Martin Panteraa0da862015-09-23 05:28:13 +00001129* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
1130 compared within and across their types. They compare lexicographically using
1131 the numeric values of their elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001132
Martin Panteraa0da862015-09-23 05:28:13 +00001133* Strings (instances of :class:`str`) compare lexicographically using the
1134 numerical Unicode code points (the result of the built-in function
1135 :func:`ord`) of their characters. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001136
Martin Panteraa0da862015-09-23 05:28:13 +00001137 Strings and binary sequences cannot be directly compared.
Georg Brandl116aa622007-08-15 14:28:22 +00001138
Martin Panteraa0da862015-09-23 05:28:13 +00001139* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can
1140 be compared only within each of their types, with the restriction that ranges
1141 do not support order comparison. Equality comparison across these types
1142 results in unequality, and ordering comparison across these types raises
1143 :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001144
Martin Panteraa0da862015-09-23 05:28:13 +00001145 Sequences compare lexicographically using comparison of corresponding
1146 elements, whereby reflexivity of the elements is enforced.
Georg Brandl116aa622007-08-15 14:28:22 +00001147
Martin Panteraa0da862015-09-23 05:28:13 +00001148 In enforcing reflexivity of elements, the comparison of collections assumes
1149 that for a collection element ``x``, ``x == x`` is always true. Based on
1150 that assumption, element identity is compared first, and element comparison
1151 is performed only for distinct elements. This approach yields the same
1152 result as a strict element comparison would, if the compared elements are
1153 reflexive. For non-reflexive elements, the result is different than for
1154 strict element comparison, and may be surprising: The non-reflexive
1155 not-a-number values for example result in the following comparison behavior
1156 when used in a list::
1157
1158 >>> nan = float('NaN')
1159 >>> nan is nan
1160 True
1161 >>> nan == nan
1162 False <-- the defined non-reflexive behavior of NaN
1163 >>> [nan] == [nan]
1164 True <-- list enforces reflexivity and tests identity first
1165
1166 Lexicographical comparison between built-in collections works as follows:
1167
1168 - For two collections to compare equal, they must be of the same type, have
1169 the same length, and each pair of corresponding elements must compare
1170 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1171 same).
1172
1173 - Collections that support order comparison are ordered the same as their
1174 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same
1175 value as ``x <= y``). If a corresponding element does not exist, the
1176 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1177 true).
1178
1179* Mappings (instances of :class:`dict`) compare equal if and only if they have
1180 equal `(key, value)` pairs. Equality comparison of the keys and elements
1181 enforces reflexivity.
1182
1183 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
1184
1185* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within
1186 and across their types.
1187
1188 They define order
1189 comparison operators to mean subset and superset tests. Those relations do
1190 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}``
1191 are not equal, nor subsets of one another, nor supersets of one
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001192 another). Accordingly, sets are not appropriate arguments for functions
Martin Panteraa0da862015-09-23 05:28:13 +00001193 which depend on total ordering (for example, :func:`min`, :func:`max`, and
1194 :func:`sorted` produce undefined results given a list of sets as inputs).
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001195
Martin Panteraa0da862015-09-23 05:28:13 +00001196 Comparison of sets enforces reflexivity of its elements.
Georg Brandl116aa622007-08-15 14:28:22 +00001197
Martin Panteraa0da862015-09-23 05:28:13 +00001198* Most other built-in types have no comparison methods implemented, so they
1199 inherit the default comparison behavior.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001200
Martin Panteraa0da862015-09-23 05:28:13 +00001201User-defined classes that customize their comparison behavior should follow
1202some consistency rules, if possible:
1203
1204* Equality comparison should be reflexive.
1205 In other words, identical objects should compare equal:
1206
1207 ``x is y`` implies ``x == y``
1208
1209* Comparison should be symmetric.
1210 In other words, the following expressions should have the same result:
1211
1212 ``x == y`` and ``y == x``
1213
1214 ``x != y`` and ``y != x``
1215
1216 ``x < y`` and ``y > x``
1217
1218 ``x <= y`` and ``y >= x``
1219
1220* Comparison should be transitive.
1221 The following (non-exhaustive) examples illustrate that:
1222
1223 ``x > y and y > z`` implies ``x > z``
1224
1225 ``x < y and y <= z`` implies ``x < z``
1226
1227* Inverse comparison should result in the boolean negation.
1228 In other words, the following expressions should have the same result:
1229
1230 ``x == y`` and ``not x != y``
1231
1232 ``x < y`` and ``not x >= y`` (for total ordering)
1233
1234 ``x > y`` and ``not x <= y`` (for total ordering)
1235
1236 The last two expressions apply to totally ordered collections (e.g. to
1237 sequences, but not to sets or mappings). See also the
1238 :func:`~functools.total_ordering` decorator.
1239
1240Python does not enforce these consistency rules. In fact, the not-a-number
1241values are an example for not following these rules.
1242
1243
1244.. _in:
1245.. _not in:
Georg Brandl495f7b52009-10-27 15:28:25 +00001246.. _membership-test-details:
1247
Martin Panteraa0da862015-09-23 05:28:13 +00001248Membership test operations
1249--------------------------
1250
Georg Brandl96593ed2007-09-07 14:15:41 +00001251The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
1252s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not
1253in s`` returns the negation of ``x in s``. All built-in sequences and set types
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001254support this as well as dictionary, for which :keyword:`in` tests whether the
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001255dictionary has a given key. For container types such as list, tuple, set,
Raymond Hettinger0cc818f2008-11-21 10:40:51 +00001256frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001257to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001258
Georg Brandl4b491312007-08-31 09:22:56 +00001259For the string and bytes types, ``x in y`` is true if and only if *x* is a
1260substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1261always considered to be a substring of any other string, so ``"" in "abc"`` will
1262return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001263
Georg Brandl116aa622007-08-15 14:28:22 +00001264For user-defined classes which define the :meth:`__contains__` method, ``x in
1265y`` is true if and only if ``y.__contains__(x)`` is true.
1266
Georg Brandl495f7b52009-10-27 15:28:25 +00001267For user-defined classes which do not define :meth:`__contains__` but do define
1268:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1269produced while iterating over ``y``. If an exception is raised during the
1270iteration, it is as if :keyword:`in` raised that exception.
1271
1272Lastly, the old-style iteration protocol is tried: if a class defines
Georg Brandl116aa622007-08-15 14:28:22 +00001273:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1274integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001275raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001276if :keyword:`in` raised that exception).
1277
1278.. index::
1279 operator: in
1280 operator: not in
1281 pair: membership; test
1282 object: sequence
1283
1284The operator :keyword:`not in` is defined to have the inverse true value of
1285:keyword:`in`.
1286
1287.. index::
1288 operator: is
1289 operator: is not
1290 pair: identity; test
1291
Martin Panteraa0da862015-09-23 05:28:13 +00001292
1293.. _is:
1294.. _is not:
1295
1296Identity comparisons
1297--------------------
1298
Georg Brandl116aa622007-08-15 14:28:22 +00001299The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1300is y`` is true if and only if *x* and *y* are the same object. ``x is not y``
Benjamin Peterson41181742008-07-02 20:22:54 +00001301yields the inverse truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001302
1303
1304.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001305.. _and:
1306.. _or:
1307.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001308
1309Boolean operations
1310==================
1311
1312.. index::
1313 pair: Conditional; expression
1314 pair: Boolean; operation
1315
Georg Brandl116aa622007-08-15 14:28:22 +00001316.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001317 or_test: `and_test` | `or_test` "or" `and_test`
1318 and_test: `not_test` | `and_test` "and" `not_test`
1319 not_test: `comparison` | "not" `not_test`
1320
1321In the context of Boolean operations, and also when expressions are used by
1322control flow statements, the following values are interpreted as false:
1323``False``, ``None``, numeric zero of all types, and empty strings and containers
1324(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001325other values are interpreted as true. User-defined objects can customize their
1326truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001327
1328.. index:: operator: not
1329
1330The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1331otherwise.
1332
Georg Brandl116aa622007-08-15 14:28:22 +00001333.. index:: operator: and
1334
1335The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1336returned; otherwise, *y* is evaluated and the resulting value is returned.
1337
1338.. index:: operator: or
1339
1340The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1341returned; otherwise, *y* is evaluated and the resulting value is returned.
1342
1343(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1344they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001345argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001346replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001347the desired value. Because :keyword:`not` has to create a new value, it
1348returns a boolean value regardless of the type of its argument
1349(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001350
1351
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001352Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001353=======================
1354
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001355.. index::
1356 pair: conditional; expression
1357 pair: ternary; operator
1358
1359.. productionlist::
1360 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001361 expression: `conditional_expression` | `lambda_expr`
1362 expression_nocond: `or_test` | `lambda_expr_nocond`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001363
1364Conditional expressions (sometimes called a "ternary operator") have the lowest
1365priority of all Python operations.
1366
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001367The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1368If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001369evaluated and its value is returned.
1370
1371See :pep:`308` for more details about conditional expressions.
1372
1373
Georg Brandl116aa622007-08-15 14:28:22 +00001374.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001375.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001376
1377Lambdas
1378=======
1379
1380.. index::
1381 pair: lambda; expression
1382 pair: lambda; form
1383 pair: anonymous; function
1384
1385.. productionlist::
Georg Brandl242e6a02013-10-06 10:28:39 +02001386 lambda_expr: "lambda" [`parameter_list`]: `expression`
1387 lambda_expr_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001388
Zachary Ware2f78b842014-06-03 09:32:40 -05001389Lambda expressions (sometimes called lambda forms) are used to create anonymous
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001390functions. The expression ``lambda arguments: expression`` yields a function
1391object. The unnamed object behaves like a function object defined with ::
Georg Brandl116aa622007-08-15 14:28:22 +00001392
Georg Brandl96593ed2007-09-07 14:15:41 +00001393 def <lambda>(arguments):
Georg Brandl116aa622007-08-15 14:28:22 +00001394 return expression
1395
1396See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001397functions created with lambda expressions cannot contain statements or
1398annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001399
Georg Brandl116aa622007-08-15 14:28:22 +00001400
1401.. _exprlists:
1402
1403Expression lists
1404================
1405
1406.. index:: pair: expression; list
1407
1408.. productionlist::
1409 expression_list: `expression` ( "," `expression` )* [","]
1410
1411.. index:: object: tuple
1412
1413An expression list containing at least one comma yields a tuple. The length of
1414the tuple is the number of expressions in the list. The expressions are
1415evaluated from left to right.
1416
1417.. index:: pair: trailing; comma
1418
1419The trailing comma is required only to create a single tuple (a.k.a. a
1420*singleton*); it is optional in all other cases. A single expression without a
1421trailing comma doesn't create a tuple, but rather yields the value of that
1422expression. (To create an empty tuple, use an empty pair of parentheses:
1423``()``.)
1424
1425
1426.. _evalorder:
1427
1428Evaluation order
1429================
1430
1431.. index:: pair: evaluation; order
1432
Georg Brandl96593ed2007-09-07 14:15:41 +00001433Python evaluates expressions from left to right. Notice that while evaluating
1434an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001435
1436In the following lines, expressions will be evaluated in the arithmetic order of
1437their suffixes::
1438
1439 expr1, expr2, expr3, expr4
1440 (expr1, expr2, expr3, expr4)
1441 {expr1: expr2, expr3: expr4}
1442 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001443 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001444 expr3, expr4 = expr1, expr2
1445
1446
1447.. _operator-summary:
1448
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001449Operator precedence
1450===================
Georg Brandl116aa622007-08-15 14:28:22 +00001451
1452.. index:: pair: operator; precedence
1453
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001454The following table summarizes the operator precedence in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001455precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001456the same box have the same precedence. Unless the syntax is explicitly given,
1457operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001458exponentiation, which groups from right to left).
1459
1460Note that comparisons, membership tests, and identity tests, all have the same
1461precedence and have a left-to-right chaining feature as described in the
1462:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001463
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001464
1465+-----------------------------------------------+-------------------------------------+
1466| Operator | Description |
1467+===============================================+=====================================+
1468| :keyword:`lambda` | Lambda expression |
1469+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001470| :keyword:`if` -- :keyword:`else` | Conditional expression |
1471+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001472| :keyword:`or` | Boolean OR |
1473+-----------------------------------------------+-------------------------------------+
1474| :keyword:`and` | Boolean AND |
1475+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001476| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001477+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001478| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001479| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001480| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001481+-----------------------------------------------+-------------------------------------+
1482| ``|`` | Bitwise OR |
1483+-----------------------------------------------+-------------------------------------+
1484| ``^`` | Bitwise XOR |
1485+-----------------------------------------------+-------------------------------------+
1486| ``&`` | Bitwise AND |
1487+-----------------------------------------------+-------------------------------------+
1488| ``<<``, ``>>`` | Shifts |
1489+-----------------------------------------------+-------------------------------------+
1490| ``+``, ``-`` | Addition and subtraction |
1491+-----------------------------------------------+-------------------------------------+
Benjamin Petersond51374e2014-04-09 23:55:56 -04001492| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
1493| | multiplication division, |
1494| | remainder [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001495+-----------------------------------------------+-------------------------------------+
1496| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1497+-----------------------------------------------+-------------------------------------+
1498| ``**`` | Exponentiation [#]_ |
1499+-----------------------------------------------+-------------------------------------+
Yury Selivanovf3e40fa2015-05-21 11:50:30 -04001500| ``await`` ``x`` | Await expression |
1501+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001502| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1503| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1504+-----------------------------------------------+-------------------------------------+
1505| ``(expressions...)``, | Binding or tuple display, |
1506| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001507| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001508| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001509+-----------------------------------------------+-------------------------------------+
1510
Georg Brandl116aa622007-08-15 14:28:22 +00001511
1512.. rubric:: Footnotes
1513
Georg Brandl116aa622007-08-15 14:28:22 +00001514.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1515 true numerically due to roundoff. For example, and assuming a platform on which
1516 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1517 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001518 1e100``, which is numerically exactly equal to ``1e100``. The function
1519 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001520 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1521 is more appropriate depends on the application.
1522
1523.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001524 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001525 cases, Python returns the latter result, in order to preserve that
1526 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1527
Martin Panteraa0da862015-09-23 05:28:13 +00001528.. [#] The Unicode standard distinguishes between :dfn:`code points`
1529 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
1530 While most abstract characters in Unicode are only represented using one
1531 code point, there is a number of abstract characters that can in addition be
1532 represented using a sequence of more than one code point. For example, the
1533 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
1534 as a single :dfn:`precomposed character` at code position U+00C7, or as a
1535 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
1536 LETTER C), followed by a :dfn:`combining character` at code position U+0327
1537 (COMBINING CEDILLA).
1538
1539 The comparison operators on strings compare at the level of Unicode code
1540 points. This may be counter-intuitive to humans. For example,
1541 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1542 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".
1543
1544 To compare strings at the level of abstract characters (that is, in a way
1545 intuitive to humans), use :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001546
Georg Brandl48310cd2009-01-03 21:18:54 +00001547.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001548 descriptors, you may notice seemingly unusual behaviour in certain uses of
1549 the :keyword:`is` operator, like those involving comparisons between instance
1550 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001551
Georg Brandl063f2372010-12-01 15:32:43 +00001552.. [#] The ``%`` operator is also used for string formatting; the same
1553 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001554
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001555.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1556 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.