blob: 12f9f2f48575aaf506f83bda8924a88cd6eb5304 [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
328generator. That generator then controls the execution of a generator function.
329The 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
374 Added ``yield from <expr>`` to delegate control flow to a subiterator
375
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
393
R David Murray2c1d1d62012-08-17 20:48:59 -0400394Generator-iterator methods
395^^^^^^^^^^^^^^^^^^^^^^^^^^
396
397This subsection describes the methods of a generator iterator. They can
398be used to control the execution of a generator function.
399
400Note that calling any of the generator methods below when the generator
401is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403.. index:: exception: StopIteration
404
405
Georg Brandl96593ed2007-09-07 14:15:41 +0000406.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000407
Georg Brandl96593ed2007-09-07 14:15:41 +0000408 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500409 executed yield expression. When a generator function is resumed with a
410 :meth:`~generator.__next__` method, the current yield expression always
411 evaluates to :const:`None`. The execution then continues to the next yield
412 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300413 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500414 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000415 exception is raised.
416
417 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
418 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420
421.. method:: generator.send(value)
422
423 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500424 *value* argument becomes the result of the current yield expression. The
425 :meth:`send` method returns the next value yielded by the generator, or
426 raises :exc:`StopIteration` if the generator exits without yielding another
427 value. When :meth:`send` is called to start the generator, it must be called
428 with :const:`None` as the argument, because there is no yield expression that
429 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431
432.. method:: generator.throw(type[, value[, traceback]])
433
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700434 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000435 and returns the next value yielded by the generator function. If the generator
436 exits without yielding another value, a :exc:`StopIteration` exception is
437 raised. If the generator function does not catch the passed-in exception, or
438 raises a different exception, then that exception propagates to the caller.
439
440.. index:: exception: GeneratorExit
441
442
443.. method:: generator.close()
444
445 Raises a :exc:`GeneratorExit` at the point where the generator function was
Georg Brandl96593ed2007-09-07 14:15:41 +0000446 paused. If the generator function then raises :exc:`StopIteration` (by
447 exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by
448 not catching the exception), close returns to its caller. If the generator
449 yields a value, a :exc:`RuntimeError` is raised. If the generator raises any
450 other exception, it is propagated to the caller. :meth:`close` does nothing
451 if the generator has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000452
Chris Jerdonek2654b862012-12-23 15:31:57 -0800453.. index:: single: yield; examples
454
455Examples
456^^^^^^^^
457
Georg Brandl116aa622007-08-15 14:28:22 +0000458Here is a simple example that demonstrates the behavior of generators and
459generator functions::
460
461 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000462 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000463 ... try:
464 ... while True:
465 ... try:
466 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000467 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000468 ... value = e
469 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000470 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000471 ...
472 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000473 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000474 Execution starts when 'next()' is called for the first time.
475 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000476 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000477 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000478 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000479 2
480 >>> generator.throw(TypeError, "spam")
481 TypeError('spam',)
482 >>> generator.close()
483 Don't forget to clean up when 'close()' is called.
484
Chris Jerdonek2654b862012-12-23 15:31:57 -0800485For examples using ``yield from``, see :ref:`pep-380` in "What's New in
486Python."
487
Georg Brandl116aa622007-08-15 14:28:22 +0000488
Georg Brandl116aa622007-08-15 14:28:22 +0000489.. _primaries:
490
491Primaries
492=========
493
494.. index:: single: primary
495
496Primaries represent the most tightly bound operations of the language. Their
497syntax is:
498
499.. productionlist::
500 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
501
502
503.. _attribute-references:
504
505Attribute references
506--------------------
507
508.. index:: pair: attribute; reference
509
510An attribute reference is a primary followed by a period and a name:
511
512.. productionlist::
513 attributeref: `primary` "." `identifier`
514
515.. index::
516 exception: AttributeError
517 object: module
518 object: list
519
520The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000521references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700522attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500523overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700524the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
525the object produced is determined by the object. Multiple evaluations of the
526same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000527
528
529.. _subscriptions:
530
531Subscriptions
532-------------
533
534.. index:: single: subscription
535
536.. index::
537 object: sequence
538 object: mapping
539 object: string
540 object: tuple
541 object: list
542 object: dictionary
543 pair: sequence; item
544
545A subscription selects an item of a sequence (string, tuple or list) or mapping
546(dictionary) object:
547
548.. productionlist::
549 subscription: `primary` "[" `expression_list` "]"
550
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700551The primary must evaluate to an object that supports subscription (lists or
552dictionaries for example). User-defined objects can support subscription by
553defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000554
555For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000556
557If the primary is a mapping, the expression list must evaluate to an object
558whose value is one of the keys of the mapping, and the subscription selects the
559value in the mapping that corresponds to that key. (The expression list is a
560tuple except if it has exactly one item.)
561
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000562If the primary is a sequence, the expression (list) must evaluate to an integer
563or a slice (as discussed in the following section).
564
565The formal syntax makes no special provision for negative indices in
566sequences; however, built-in sequences all provide a :meth:`__getitem__`
567method that interprets negative indices by adding the length of the sequence
568to the index (so that ``x[-1]`` selects the last item of ``x``). The
569resulting value must be a nonnegative integer less than the number of items in
570the sequence, and the subscription selects the item whose index is that value
571(counting from zero). Since the support for negative indices and slicing
572occurs in the object's :meth:`__getitem__` method, subclasses overriding
573this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000574
575.. index::
576 single: character
577 pair: string; item
578
579A string's items are characters. A character is not a separate data type but a
580string of exactly one character.
581
582
583.. _slicings:
584
585Slicings
586--------
587
588.. index::
589 single: slicing
590 single: slice
591
592.. index::
593 object: sequence
594 object: string
595 object: tuple
596 object: list
597
598A slicing selects a range of items in a sequence object (e.g., a string, tuple
599or list). Slicings may be used as expressions or as targets in assignment or
600:keyword:`del` statements. The syntax for a slicing:
601
602.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000603 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000604 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000605 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000606 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000607 lower_bound: `expression`
608 upper_bound: `expression`
609 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000610
611There is ambiguity in the formal syntax here: anything that looks like an
612expression list also looks like a slice list, so any subscription can be
613interpreted as a slicing. Rather than further complicating the syntax, this is
614disambiguated by defining that in this case the interpretation as a subscription
615takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000616slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000617
618.. index::
619 single: start (slice object attribute)
620 single: stop (slice object attribute)
621 single: step (slice object attribute)
622
Georg Brandla4c8c472014-10-31 10:38:49 +0100623The semantics for a slicing are as follows. The primary is indexed (using the
624same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000625normal subscription) with a key that is constructed from the slice list, as
626follows. If the slice list contains at least one comma, the key is a tuple
627containing the conversion of the slice items; otherwise, the conversion of the
628lone slice item is the key. The conversion of a slice item that is an
629expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300630object (see section :ref:`types`) whose :attr:`~slice.start`,
631:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
632expressions given as lower bound, upper bound and stride, respectively,
633substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000634
635
Chris Jerdonekb4309942012-12-25 14:54:44 -0800636.. index::
637 object: callable
638 single: call
639 single: argument; call semantics
640
Georg Brandl116aa622007-08-15 14:28:22 +0000641.. _calls:
642
643Calls
644-----
645
Chris Jerdonekb4309942012-12-25 14:54:44 -0800646A call calls a callable object (e.g., a :term:`function`) with a possibly empty
647series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000648
649.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000650 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000651 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000652 : ["," "*" `expression`] ["," `keyword_arguments`]
653 : ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000654 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000655 : ["," `keyword_arguments`] ["," "**" `expression`]
656 : | "*" `expression` ["," `keyword_arguments`] ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000657 : | "**" `expression`
658 positional_arguments: `expression` ("," `expression`)*
659 keyword_arguments: `keyword_item` ("," `keyword_item`)*
660 keyword_item: `identifier` "=" `expression`
661
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700662An optional trailing comma may be present after the positional and keyword arguments
663but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000664
Chris Jerdonekb4309942012-12-25 14:54:44 -0800665.. index::
666 single: parameter; call semantics
667
Georg Brandl116aa622007-08-15 14:28:22 +0000668The primary must evaluate to a callable object (user-defined functions, built-in
669functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000670instances, and all objects having a :meth:`__call__` method are callable). All
671argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800672to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000673
674.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000675
676If keyword arguments are present, they are first converted to positional
677arguments, as follows. First, a list of unfilled slots is created for the
678formal parameters. If there are N positional arguments, they are placed in the
679first N slots. Next, for each keyword argument, the identifier is used to
680determine the corresponding slot (if the identifier is the same as the first
681formal parameter name, the first slot is used, and so on). If the slot is
682already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
683the argument is placed in the slot, filling it (even if the expression is
684``None``, it fills the slot). When all arguments have been processed, the slots
685that are still unfilled are filled with the corresponding default value from the
686function definition. (Default values are calculated, once, when the function is
687defined; thus, a mutable object such as a list or dictionary used as default
688value will be shared by all calls that don't specify an argument value for the
689corresponding slot; this should usually be avoided.) If there are any unfilled
690slots for which no default value is specified, a :exc:`TypeError` exception is
691raised. Otherwise, the list of filled slots is used as the argument list for
692the call.
693
Georg Brandl495f7b52009-10-27 15:28:25 +0000694.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000695
Georg Brandl495f7b52009-10-27 15:28:25 +0000696 An implementation may provide built-in functions whose positional parameters
697 do not have names, even if they are 'named' for the purpose of documentation,
698 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000699 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000700 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000701
Georg Brandl116aa622007-08-15 14:28:22 +0000702If there are more positional arguments than there are formal parameter slots, a
703:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
704``*identifier`` is present; in this case, that formal parameter receives a tuple
705containing the excess positional arguments (or an empty tuple if there were no
706excess positional arguments).
707
708If any keyword argument does not correspond to a formal parameter name, a
709:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
710``**identifier`` is present; in this case, that formal parameter receives a
711dictionary containing the excess keyword arguments (using the keywords as keys
712and the argument values as corresponding values), or a (new) empty dictionary if
713there were no excess keyword arguments.
714
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300715.. index::
716 single: *; in function calls
717
Georg Brandl116aa622007-08-15 14:28:22 +0000718If the syntax ``*expression`` appears in the function call, ``expression`` must
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300719evaluate to an iterable. Elements from this iterable are treated as if they
720were additional positional arguments; if there are positional arguments
Ezio Melotti59256322011-07-30 21:25:22 +0300721*x1*, ..., *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*,
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300722this is equivalent to a call with M+N positional arguments *x1*, ..., *xN*,
723*y1*, ..., *yM*.
Georg Brandl116aa622007-08-15 14:28:22 +0000724
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000725A consequence of this is that although the ``*expression`` syntax may appear
726*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000727(and the ``**expression`` argument, if any -- see below). So::
728
729 >>> def f(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000730 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000731 ...
732 >>> f(b=1, *(2,))
733 2 1
734 >>> f(a=1, *(2,))
735 Traceback (most recent call last):
736 File "<stdin>", line 1, in ?
737 TypeError: f() got multiple values for keyword argument 'a'
738 >>> f(1, *(2,))
739 1 2
740
741It is unusual for both keyword arguments and the ``*expression`` syntax to be
742used in the same call, so in practice this confusion does not arise.
743
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300744.. index::
745 single: **; in function calls
746
Georg Brandl116aa622007-08-15 14:28:22 +0000747If the syntax ``**expression`` appears in the function call, ``expression`` must
748evaluate to a mapping, the contents of which are treated as additional keyword
749arguments. In the case of a keyword appearing in both ``expression`` and as an
750explicit keyword argument, a :exc:`TypeError` exception is raised.
751
752Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
753used as positional argument slots or as keyword argument names.
754
755A call always returns some value, possibly ``None``, unless it raises an
756exception. How this value is computed depends on the type of the callable
757object.
758
759If it is---
760
761a user-defined function:
762 .. index::
763 pair: function; call
764 triple: user-defined; function; call
765 object: user-defined function
766 object: function
767
768 The code block for the function is executed, passing it the argument list. The
769 first thing the code block will do is bind the formal parameters to the
770 arguments; this is described in section :ref:`function`. When the code block
771 executes a :keyword:`return` statement, this specifies the return value of the
772 function call.
773
774a built-in function or method:
775 .. index::
776 pair: function; call
777 pair: built-in function; call
778 pair: method; call
779 pair: built-in method; call
780 object: built-in method
781 object: built-in function
782 object: method
783 object: function
784
785 The result is up to the interpreter; see :ref:`built-in-funcs` for the
786 descriptions of built-in functions and methods.
787
788a class object:
789 .. index::
790 object: class
791 pair: class object; call
792
793 A new instance of that class is returned.
794
795a class instance method:
796 .. index::
797 object: class instance
798 object: instance
799 pair: class instance; call
800
801 The corresponding user-defined function is called, with an argument list that is
802 one longer than the argument list of the call: the instance becomes the first
803 argument.
804
805a class instance:
806 .. index::
807 pair: instance; call
808 single: __call__() (object method)
809
810 The class must define a :meth:`__call__` method; the effect is then the same as
811 if that method was called.
812
813
814.. _power:
815
816The power operator
817==================
818
819The power operator binds more tightly than unary operators on its left; it binds
820less tightly than unary operators on its right. The syntax is:
821
822.. productionlist::
823 power: `primary` ["**" `u_expr`]
824
825Thus, in an unparenthesized sequence of power and unary operators, the operators
826are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +0000827for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000828
829The power operator has the same semantics as the built-in :func:`pow` function,
830when called with two arguments: it yields its left argument raised to the power
831of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +0000832type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +0000833
Georg Brandl96593ed2007-09-07 14:15:41 +0000834For int operands, the result has the same type as the operands unless the second
835argument is negative; in that case, all arguments are converted to float and a
836float result is delivered. For example, ``10**2`` returns ``100``, but
837``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +0000838
839Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +0000840Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +0000841number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000842
843
844.. _unary:
845
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000846Unary arithmetic and bitwise operations
847=======================================
Georg Brandl116aa622007-08-15 14:28:22 +0000848
849.. index::
850 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +0000851 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000852
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000853All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +0000854
855.. productionlist::
856 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
857
858.. index::
859 single: negation
860 single: minus
861
862The unary ``-`` (minus) operator yields the negation of its numeric argument.
863
864.. index:: single: plus
865
866The unary ``+`` (plus) operator yields its numeric argument unchanged.
867
868.. index:: single: inversion
869
Christian Heimesfaf2f632008-01-06 16:59:19 +0000870
Georg Brandl95817b32008-05-11 14:30:18 +0000871The unary ``~`` (invert) operator yields the bitwise inversion of its integer
872argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
873applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000874
875.. index:: exception: TypeError
876
877In all three cases, if the argument does not have the proper type, a
878:exc:`TypeError` exception is raised.
879
880
881.. _binary:
882
883Binary arithmetic operations
884============================
885
886.. index:: triple: binary; arithmetic; operation
887
888The binary arithmetic operations have the conventional priority levels. Note
889that some of these operations also apply to certain non-numeric types. Apart
890from the power operator, there are only two levels, one for multiplicative
891operators and one for additive operators:
892
893.. productionlist::
Benjamin Petersond51374e2014-04-09 23:55:56 -0400894 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
895 : `m_expr` "//" `u_expr`| `m_expr` "/" `u_expr` |
896 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +0000897 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
898
899.. index:: single: multiplication
900
901The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +0000902arguments must either both be numbers, or one argument must be an integer and
903the other must be a sequence. In the former case, the numbers are converted to a
904common type and then multiplied together. In the latter case, sequence
905repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000906
Benjamin Petersond51374e2014-04-09 23:55:56 -0400907.. index:: single: matrix multiplication
908
909The ``@`` (at) operator is intended to be used for matrix multiplication. No
910builtin Python types implement this operator.
911
912.. versionadded:: 3.5
913
Georg Brandl116aa622007-08-15 14:28:22 +0000914.. index::
915 exception: ZeroDivisionError
916 single: division
917
918The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
919their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +0200920Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +0000921integer; the result is that of mathematical division with the 'floor' function
922applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
923exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000924
925.. index:: single: modulo
926
927The ``%`` (modulo) operator yields the remainder from the division of the first
928argument by the second. The numeric arguments are first converted to a common
929type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
930arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
931(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
932result with the same sign as its second operand (or zero); the absolute value of
933the result is strictly smaller than the absolute value of the second operand
934[#]_.
935
Georg Brandl96593ed2007-09-07 14:15:41 +0000936The floor division and modulo operators are connected by the following
937identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
938connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
939x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000940
941In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +0000942also overloaded by string objects to perform old-style string formatting (also
943known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +0000944Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +0000945
946The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +0000947function are not defined for complex numbers. Instead, convert to a floating
948point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +0000949
950.. index:: single: addition
951
Georg Brandl96593ed2007-09-07 14:15:41 +0000952The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700953must either both be numbers or both be sequences of the same type. In the
954former case, the numbers are converted to a common type and then added together.
955In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +0000956
957.. index:: single: subtraction
958
959The ``-`` (subtraction) operator yields the difference of its arguments. The
960numeric arguments are first converted to a common type.
961
962
963.. _shifting:
964
965Shifting operations
966===================
967
968.. index:: pair: shifting; operation
969
970The shifting operations have lower priority than the arithmetic operations:
971
972.. productionlist::
973 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
974
Georg Brandl96593ed2007-09-07 14:15:41 +0000975These operators accept integers as arguments. They shift the first argument to
976the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000977
978.. index:: exception: ValueError
979
Georg Brandl0aaae262013-10-08 21:47:18 +0200980A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
981shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000982
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000983.. note::
984
985 In the current implementation, the right-hand operand is required
Mark Dickinson505add32010-04-06 18:22:06 +0000986 to be at most :attr:`sys.maxsize`. If the right-hand operand is larger than
987 :attr:`sys.maxsize` an :exc:`OverflowError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000988
989.. _bitwise:
990
Christian Heimesfaf2f632008-01-06 16:59:19 +0000991Binary bitwise operations
992=========================
Georg Brandl116aa622007-08-15 14:28:22 +0000993
Christian Heimesfaf2f632008-01-06 16:59:19 +0000994.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000995
996Each of the three bitwise operations has a different priority level:
997
998.. productionlist::
999 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1000 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1001 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1002
Christian Heimesfaf2f632008-01-06 16:59:19 +00001003.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +00001004
Georg Brandl96593ed2007-09-07 14:15:41 +00001005The ``&`` operator yields the bitwise AND of its arguments, which must be
1006integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001007
1008.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001009 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001010 pair: exclusive; or
1011
1012The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001013must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001014
1015.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001016 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001017 pair: inclusive; or
1018
1019The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001020must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001021
1022
1023.. _comparisons:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001024.. _is:
Georg Brandl375aec22011-01-15 17:03:02 +00001025.. _is not:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001026.. _in:
Georg Brandl375aec22011-01-15 17:03:02 +00001027.. _not in:
Georg Brandl116aa622007-08-15 14:28:22 +00001028
1029Comparisons
1030===========
1031
1032.. index:: single: comparison
1033
1034.. index:: pair: C; language
1035
1036Unlike C, all comparison operations in Python have the same priority, which is
1037lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1038C, expressions like ``a < b < c`` have the interpretation that is conventional
1039in mathematics:
1040
1041.. productionlist::
1042 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1043 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1044 : | "is" ["not"] | ["not"] "in"
1045
1046Comparisons yield boolean values: ``True`` or ``False``.
1047
1048.. index:: pair: chaining; comparisons
1049
1050Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1051``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1052cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1053
Guido van Rossum04110fb2007-08-24 16:32:05 +00001054Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1055*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1056to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1057evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001058
Guido van Rossum04110fb2007-08-24 16:32:05 +00001059Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001060*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1061pretty).
1062
1063The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1064values of two objects. The objects need not have the same type. If both are
Georg Brandl9609cea2008-09-09 19:31:57 +00001065numbers, they are converted to a common type. Otherwise, the ``==`` and ``!=``
1066operators *always* consider objects of different types to be unequal, while the
1067``<``, ``>``, ``>=`` and ``<=`` operators raise a :exc:`TypeError` when
1068comparing objects of different types that do not implement these operators for
1069the given pair of types. You can control comparison behavior of objects of
Georg Brandl22b34312009-07-26 14:54:51 +00001070non-built-in types by defining rich comparison methods like :meth:`__gt__`,
Georg Brandl9609cea2008-09-09 19:31:57 +00001071described in section :ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001072
1073Comparison of objects of the same type depends on the type:
1074
1075* Numbers are compared arithmetically.
1076
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001077* The values :const:`float('NaN')` and :const:`Decimal('NaN')` are special.
Zachary Ware57c616f2015-02-19 22:15:36 -06001078 They are identical to themselves, ``x is x`` but are not equal to themselves,
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001079 ``x != x``. Additionally, comparing any value to a not-a-number value
1080 will return ``False``. For example, both ``3 < float('NaN')`` and
1081 ``float('NaN') < 3`` will return ``False``.
1082
Georg Brandl96593ed2007-09-07 14:15:41 +00001083* Bytes objects are compared lexicographically using the numeric values of their
1084 elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001085
Georg Brandl116aa622007-08-15 14:28:22 +00001086* Strings are compared lexicographically using the numeric equivalents (the
Georg Brandl96593ed2007-09-07 14:15:41 +00001087 result of the built-in function :func:`ord`) of their characters. [#]_ String
1088 and bytes object can't be compared!
Georg Brandl116aa622007-08-15 14:28:22 +00001089
1090* Tuples and lists are compared lexicographically using comparison of
1091 corresponding elements. This means that to compare equal, each element must
1092 compare equal and the two sequences must be of the same type and have the same
1093 length.
1094
1095 If not equal, the sequences are ordered the same as their first differing
Mark Dickinsonc48d8342009-02-01 14:18:10 +00001096 elements. For example, ``[1,2,x] <= [1,2,y]`` has the same value as
1097 ``x <= y``. If the corresponding element does not exist, the shorter
Georg Brandl96593ed2007-09-07 14:15:41 +00001098 sequence is ordered first (for example, ``[1,2] < [1,2,3]``).
Georg Brandl116aa622007-08-15 14:28:22 +00001099
Senthil Kumaran07367672010-07-14 20:30:02 +00001100* Mappings (dictionaries) compare equal if and only if they have the same
1101 ``(key, value)`` pairs. Order comparisons ``('<', '<=', '>=', '>')``
1102 raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001103
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001104* Sets and frozensets define comparison operators to mean subset and superset
1105 tests. Those relations do not define total orderings (the two sets ``{1,2}``
1106 and {2,3} are not equal, nor subsets of one another, nor supersets of one
1107 another). Accordingly, sets are not appropriate arguments for functions
1108 which depend on total ordering. For example, :func:`min`, :func:`max`, and
1109 :func:`sorted` produce undefined results given a list of sets as inputs.
1110
Georg Brandl22b34312009-07-26 14:54:51 +00001111* Most other objects of built-in types compare unequal unless they are the same
Georg Brandl116aa622007-08-15 14:28:22 +00001112 object; the choice whether one object is considered smaller or larger than
1113 another one is made arbitrarily but consistently within one execution of a
1114 program.
1115
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001116Comparison of objects of differing types depends on whether either of the
Georg Brandl7ea9a422012-10-06 13:48:39 +02001117types provide explicit support for the comparison. Most numeric types can be
1118compared with one another. When cross-type comparison is not supported, the
1119comparison method returns ``NotImplemented``.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001120
Georg Brandl495f7b52009-10-27 15:28:25 +00001121.. _membership-test-details:
1122
Georg Brandl96593ed2007-09-07 14:15:41 +00001123The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
1124s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not
1125in s`` returns the negation of ``x in s``. All built-in sequences and set types
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001126support this as well as dictionary, for which :keyword:`in` tests whether the
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001127dictionary has a given key. For container types such as list, tuple, set,
Raymond Hettinger0cc818f2008-11-21 10:40:51 +00001128frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001129to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001130
Georg Brandl4b491312007-08-31 09:22:56 +00001131For the string and bytes types, ``x in y`` is true if and only if *x* is a
1132substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1133always considered to be a substring of any other string, so ``"" in "abc"`` will
1134return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001135
Georg Brandl116aa622007-08-15 14:28:22 +00001136For user-defined classes which define the :meth:`__contains__` method, ``x in
1137y`` is true if and only if ``y.__contains__(x)`` is true.
1138
Georg Brandl495f7b52009-10-27 15:28:25 +00001139For user-defined classes which do not define :meth:`__contains__` but do define
1140:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1141produced while iterating over ``y``. If an exception is raised during the
1142iteration, it is as if :keyword:`in` raised that exception.
1143
1144Lastly, the old-style iteration protocol is tried: if a class defines
Georg Brandl116aa622007-08-15 14:28:22 +00001145:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1146integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001147raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001148if :keyword:`in` raised that exception).
1149
1150.. index::
1151 operator: in
1152 operator: not in
1153 pair: membership; test
1154 object: sequence
1155
1156The operator :keyword:`not in` is defined to have the inverse true value of
1157:keyword:`in`.
1158
1159.. index::
1160 operator: is
1161 operator: is not
1162 pair: identity; test
1163
1164The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1165is 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 +00001166yields the inverse truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001167
1168
1169.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001170.. _and:
1171.. _or:
1172.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001173
1174Boolean operations
1175==================
1176
1177.. index::
1178 pair: Conditional; expression
1179 pair: Boolean; operation
1180
Georg Brandl116aa622007-08-15 14:28:22 +00001181.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001182 or_test: `and_test` | `or_test` "or" `and_test`
1183 and_test: `not_test` | `and_test` "and" `not_test`
1184 not_test: `comparison` | "not" `not_test`
1185
1186In the context of Boolean operations, and also when expressions are used by
1187control flow statements, the following values are interpreted as false:
1188``False``, ``None``, numeric zero of all types, and empty strings and containers
1189(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001190other values are interpreted as true. User-defined objects can customize their
1191truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001192
1193.. index:: operator: not
1194
1195The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1196otherwise.
1197
Georg Brandl116aa622007-08-15 14:28:22 +00001198.. index:: operator: and
1199
1200The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1201returned; otherwise, *y* is evaluated and the resulting value is returned.
1202
1203.. index:: operator: or
1204
1205The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1206returned; otherwise, *y* is evaluated and the resulting value is returned.
1207
1208(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1209they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001210argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001211replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001212the desired value. Because :keyword:`not` has to create a new value, it
1213returns a boolean value regardless of the type of its argument
1214(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001215
1216
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001217Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001218=======================
1219
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001220.. index::
1221 pair: conditional; expression
1222 pair: ternary; operator
1223
1224.. productionlist::
1225 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001226 expression: `conditional_expression` | `lambda_expr`
1227 expression_nocond: `or_test` | `lambda_expr_nocond`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001228
1229Conditional expressions (sometimes called a "ternary operator") have the lowest
1230priority of all Python operations.
1231
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001232The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1233If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001234evaluated and its value is returned.
1235
1236See :pep:`308` for more details about conditional expressions.
1237
1238
Georg Brandl116aa622007-08-15 14:28:22 +00001239.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001240.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001241
1242Lambdas
1243=======
1244
1245.. index::
1246 pair: lambda; expression
1247 pair: lambda; form
1248 pair: anonymous; function
1249
1250.. productionlist::
Georg Brandl242e6a02013-10-06 10:28:39 +02001251 lambda_expr: "lambda" [`parameter_list`]: `expression`
1252 lambda_expr_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001253
Zachary Ware2f78b842014-06-03 09:32:40 -05001254Lambda expressions (sometimes called lambda forms) are used to create anonymous
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001255functions. The expression ``lambda arguments: expression`` yields a function
1256object. The unnamed object behaves like a function object defined with ::
Georg Brandl116aa622007-08-15 14:28:22 +00001257
Georg Brandl96593ed2007-09-07 14:15:41 +00001258 def <lambda>(arguments):
Georg Brandl116aa622007-08-15 14:28:22 +00001259 return expression
1260
1261See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001262functions created with lambda expressions cannot contain statements or
1263annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001264
Georg Brandl116aa622007-08-15 14:28:22 +00001265
1266.. _exprlists:
1267
1268Expression lists
1269================
1270
1271.. index:: pair: expression; list
1272
1273.. productionlist::
1274 expression_list: `expression` ( "," `expression` )* [","]
1275
1276.. index:: object: tuple
1277
1278An expression list containing at least one comma yields a tuple. The length of
1279the tuple is the number of expressions in the list. The expressions are
1280evaluated from left to right.
1281
1282.. index:: pair: trailing; comma
1283
1284The trailing comma is required only to create a single tuple (a.k.a. a
1285*singleton*); it is optional in all other cases. A single expression without a
1286trailing comma doesn't create a tuple, but rather yields the value of that
1287expression. (To create an empty tuple, use an empty pair of parentheses:
1288``()``.)
1289
1290
1291.. _evalorder:
1292
1293Evaluation order
1294================
1295
1296.. index:: pair: evaluation; order
1297
Georg Brandl96593ed2007-09-07 14:15:41 +00001298Python evaluates expressions from left to right. Notice that while evaluating
1299an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001300
1301In the following lines, expressions will be evaluated in the arithmetic order of
1302their suffixes::
1303
1304 expr1, expr2, expr3, expr4
1305 (expr1, expr2, expr3, expr4)
1306 {expr1: expr2, expr3: expr4}
1307 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001308 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001309 expr3, expr4 = expr1, expr2
1310
1311
1312.. _operator-summary:
1313
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001314Operator precedence
1315===================
Georg Brandl116aa622007-08-15 14:28:22 +00001316
1317.. index:: pair: operator; precedence
1318
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001319The following table summarizes the operator precedence in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001320precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001321the same box have the same precedence. Unless the syntax is explicitly given,
1322operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001323exponentiation, which groups from right to left).
1324
1325Note that comparisons, membership tests, and identity tests, all have the same
1326precedence and have a left-to-right chaining feature as described in the
1327:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001328
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001329
1330+-----------------------------------------------+-------------------------------------+
1331| Operator | Description |
1332+===============================================+=====================================+
1333| :keyword:`lambda` | Lambda expression |
1334+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001335| :keyword:`if` -- :keyword:`else` | Conditional expression |
1336+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001337| :keyword:`or` | Boolean OR |
1338+-----------------------------------------------+-------------------------------------+
1339| :keyword:`and` | Boolean AND |
1340+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001341| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001342+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001343| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001344| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001345| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001346+-----------------------------------------------+-------------------------------------+
1347| ``|`` | Bitwise OR |
1348+-----------------------------------------------+-------------------------------------+
1349| ``^`` | Bitwise XOR |
1350+-----------------------------------------------+-------------------------------------+
1351| ``&`` | Bitwise AND |
1352+-----------------------------------------------+-------------------------------------+
1353| ``<<``, ``>>`` | Shifts |
1354+-----------------------------------------------+-------------------------------------+
1355| ``+``, ``-`` | Addition and subtraction |
1356+-----------------------------------------------+-------------------------------------+
Benjamin Petersond51374e2014-04-09 23:55:56 -04001357| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
1358| | multiplication division, |
1359| | remainder [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001360+-----------------------------------------------+-------------------------------------+
1361| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1362+-----------------------------------------------+-------------------------------------+
1363| ``**`` | Exponentiation [#]_ |
1364+-----------------------------------------------+-------------------------------------+
1365| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1366| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1367+-----------------------------------------------+-------------------------------------+
1368| ``(expressions...)``, | Binding or tuple display, |
1369| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001370| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001371| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001372+-----------------------------------------------+-------------------------------------+
1373
Georg Brandl116aa622007-08-15 14:28:22 +00001374
1375.. rubric:: Footnotes
1376
Georg Brandl116aa622007-08-15 14:28:22 +00001377.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1378 true numerically due to roundoff. For example, and assuming a platform on which
1379 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1380 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001381 1e100``, which is numerically exactly equal to ``1e100``. The function
1382 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001383 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1384 is more appropriate depends on the application.
1385
1386.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001387 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001388 cases, Python returns the latter result, in order to preserve that
1389 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1390
Georg Brandl96593ed2007-09-07 14:15:41 +00001391.. [#] While comparisons between strings make sense at the byte level, they may
1392 be counter-intuitive to users. For example, the strings ``"\u00C7"`` and
1393 ``"\u0327\u0043"`` compare differently, even though they both represent the
Georg Brandlae2dbe22009-03-13 19:04:40 +00001394 same unicode character (LATIN CAPITAL LETTER C WITH CEDILLA). To compare
Georg Brandl9afde1c2007-11-01 20:32:30 +00001395 strings in a human recognizable way, compare using
1396 :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001397
Georg Brandl48310cd2009-01-03 21:18:54 +00001398.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001399 descriptors, you may notice seemingly unusual behaviour in certain uses of
1400 the :keyword:`is` operator, like those involving comparisons between instance
1401 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001402
Georg Brandl063f2372010-12-01 15:32:43 +00001403.. [#] The ``%`` operator is also used for string formatting; the same
1404 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001405
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001406.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1407 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.