blob: 1210c701de7a3fc4cb1d1877c4ec1d46dc7e744a [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
333current bindings of local variables, the instruction pointer, and the internal
334evaluation stack. When the execution is resumed by calling one of the
335generator's methods, the function can proceed exactly as if the yield expression
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700336were just another external call. The value of the yield expression after
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500337resuming depends on the method which resumed the execution. If
338:meth:`~generator.__next__` is used (typically via either a :keyword:`for` or
339the :func:`next` builtin) then the result is :const:`None`. Otherwise, if
340:meth:`~generator.send` is used, then the result will be the value passed in to
341that method.
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343.. index:: single: coroutine
344
345All of this makes generator functions quite similar to coroutines; they yield
346multiple times, they have more than one entry point and their execution can be
347suspended. The only difference is that a generator function cannot control
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700348where the execution should continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000349transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000350
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700351Yield expressions are allowed in the :keyword:`try` clause of a :keyword:`try`
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500352... :keyword:`finally` construct. If the generator is not resumed before it is
353finalized (by reaching a zero reference count or by being garbage collected),
354the generator-iterator's :meth:`~generator.close` method will be called,
355allowing any pending :keyword:`finally` clauses to execute.
Georg Brandl02c30562007-09-07 17:52:53 +0000356
Nick Coghlan0ed80192012-01-14 14:43:24 +1000357When ``yield from <expr>`` is used, it treats the supplied expression as
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000358a subiterator. All values produced by that subiterator are passed directly
359to the caller of the current generator's methods. Any values passed in with
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300360:meth:`~generator.send` and any exceptions passed in with
361:meth:`~generator.throw` are passed to the underlying iterator if it has the
362appropriate methods. If this is not the case, then :meth:`~generator.send`
363will raise :exc:`AttributeError` or :exc:`TypeError`, while
364:meth:`~generator.throw` will just raise the passed in exception immediately.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000365
366When the underlying iterator is complete, the :attr:`~StopIteration.value`
367attribute of the raised :exc:`StopIteration` instance becomes the value of
368the yield expression. It can be either set explicitly when raising
369:exc:`StopIteration`, or automatically when the sub-iterator is a generator
370(by returning a value from the sub-generator).
371
Nick Coghlan0ed80192012-01-14 14:43:24 +1000372 .. versionchanged:: 3.3
373 Added ``yield from <expr>`` to delegate control flow to a subiterator
374
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500375The parentheses may be omitted when the yield expression is the sole expression
376on the right hand side of an assignment statement.
377
378.. seealso::
379
380 :pep:`0255` - Simple Generators
381 The proposal for adding generators and the :keyword:`yield` statement to Python.
382
383 :pep:`0342` - Coroutines via Enhanced Generators
384 The proposal to enhance the API and syntax of generators, making them
385 usable as simple coroutines.
386
387 :pep:`0380` - Syntax for Delegating to a Subgenerator
388 The proposal to introduce the :token:`yield_from` syntax, making delegation
389 to sub-generators easy.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000390
Georg Brandl116aa622007-08-15 14:28:22 +0000391.. index:: object: generator
392
R David Murray2c1d1d62012-08-17 20:48:59 -0400393Generator-iterator methods
394^^^^^^^^^^^^^^^^^^^^^^^^^^
395
396This subsection describes the methods of a generator iterator. They can
397be used to control the execution of a generator function.
398
399Note that calling any of the generator methods below when the generator
400is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402.. index:: exception: StopIteration
403
404
Georg Brandl96593ed2007-09-07 14:15:41 +0000405.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000406
Georg Brandl96593ed2007-09-07 14:15:41 +0000407 Starts the execution of a generator function or resumes it at the last
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500408 executed yield expression. When a generator function is resumed with a
409 :meth:`~generator.__next__` method, the current yield expression always
410 evaluates to :const:`None`. The execution then continues to the next yield
411 expression, where the generator is suspended again, and the value of the
Serhiy Storchaka848c8b22014-09-05 23:27:36 +0300412 :token:`expression_list` is returned to :meth:`__next__`'s caller. If the
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500413 generator exits without yielding another value, a :exc:`StopIteration`
Georg Brandl96593ed2007-09-07 14:15:41 +0000414 exception is raised.
415
416 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
417 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000418
419
420.. method:: generator.send(value)
421
422 Resumes the execution and "sends" a value into the generator function. The
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500423 *value* argument becomes the result of the current yield expression. The
424 :meth:`send` method returns the next value yielded by the generator, or
425 raises :exc:`StopIteration` if the generator exits without yielding another
426 value. When :meth:`send` is called to start the generator, it must be called
427 with :const:`None` as the argument, because there is no yield expression that
428 could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000429
430
431.. method:: generator.throw(type[, value[, traceback]])
432
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700433 Raises an exception of type ``type`` at the point where the generator was paused,
Georg Brandl116aa622007-08-15 14:28:22 +0000434 and returns the next value yielded by the generator function. If the generator
435 exits without yielding another value, a :exc:`StopIteration` exception is
436 raised. If the generator function does not catch the passed-in exception, or
437 raises a different exception, then that exception propagates to the caller.
438
439.. index:: exception: GeneratorExit
440
441
442.. method:: generator.close()
443
444 Raises a :exc:`GeneratorExit` at the point where the generator function was
Georg Brandl96593ed2007-09-07 14:15:41 +0000445 paused. If the generator function then raises :exc:`StopIteration` (by
446 exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by
447 not catching the exception), close returns to its caller. If the generator
448 yields a value, a :exc:`RuntimeError` is raised. If the generator raises any
449 other exception, it is propagated to the caller. :meth:`close` does nothing
450 if the generator has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000451
Chris Jerdonek2654b862012-12-23 15:31:57 -0800452.. index:: single: yield; examples
453
454Examples
455^^^^^^^^
456
Georg Brandl116aa622007-08-15 14:28:22 +0000457Here is a simple example that demonstrates the behavior of generators and
458generator functions::
459
460 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000461 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000462 ... try:
463 ... while True:
464 ... try:
465 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000466 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000467 ... value = e
468 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000469 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000470 ...
471 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000472 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000473 Execution starts when 'next()' is called for the first time.
474 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000475 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000476 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000477 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000478 2
479 >>> generator.throw(TypeError, "spam")
480 TypeError('spam',)
481 >>> generator.close()
482 Don't forget to clean up when 'close()' is called.
483
Chris Jerdonek2654b862012-12-23 15:31:57 -0800484For examples using ``yield from``, see :ref:`pep-380` in "What's New in
485Python."
486
Georg Brandl116aa622007-08-15 14:28:22 +0000487
Georg Brandl116aa622007-08-15 14:28:22 +0000488.. _primaries:
489
490Primaries
491=========
492
493.. index:: single: primary
494
495Primaries represent the most tightly bound operations of the language. Their
496syntax is:
497
498.. productionlist::
499 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
500
501
502.. _attribute-references:
503
504Attribute references
505--------------------
506
507.. index:: pair: attribute; reference
508
509An attribute reference is a primary followed by a period and a name:
510
511.. productionlist::
512 attributeref: `primary` "." `identifier`
513
514.. index::
515 exception: AttributeError
516 object: module
517 object: list
518
519The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000520references, which most objects do. This object is then asked to produce the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700521attribute whose name is the identifier. This production can be customized by
Zachary Ware2f78b842014-06-03 09:32:40 -0500522overriding the :meth:`__getattr__` method. If this attribute is not available,
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700523the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
524the object produced is determined by the object. Multiple evaluations of the
525same attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000526
527
528.. _subscriptions:
529
530Subscriptions
531-------------
532
533.. index:: single: subscription
534
535.. index::
536 object: sequence
537 object: mapping
538 object: string
539 object: tuple
540 object: list
541 object: dictionary
542 pair: sequence; item
543
544A subscription selects an item of a sequence (string, tuple or list) or mapping
545(dictionary) object:
546
547.. productionlist::
548 subscription: `primary` "[" `expression_list` "]"
549
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700550The primary must evaluate to an object that supports subscription (lists or
551dictionaries for example). User-defined objects can support subscription by
552defining a :meth:`__getitem__` method.
Georg Brandl96593ed2007-09-07 14:15:41 +0000553
554For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556If the primary is a mapping, the expression list must evaluate to an object
557whose value is one of the keys of the mapping, and the subscription selects the
558value in the mapping that corresponds to that key. (The expression list is a
559tuple except if it has exactly one item.)
560
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000561If the primary is a sequence, the expression (list) must evaluate to an integer
562or a slice (as discussed in the following section).
563
564The formal syntax makes no special provision for negative indices in
565sequences; however, built-in sequences all provide a :meth:`__getitem__`
566method that interprets negative indices by adding the length of the sequence
567to the index (so that ``x[-1]`` selects the last item of ``x``). The
568resulting value must be a nonnegative integer less than the number of items in
569the sequence, and the subscription selects the item whose index is that value
570(counting from zero). Since the support for negative indices and slicing
571occurs in the object's :meth:`__getitem__` method, subclasses overriding
572this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000573
574.. index::
575 single: character
576 pair: string; item
577
578A string's items are characters. A character is not a separate data type but a
579string of exactly one character.
580
581
582.. _slicings:
583
584Slicings
585--------
586
587.. index::
588 single: slicing
589 single: slice
590
591.. index::
592 object: sequence
593 object: string
594 object: tuple
595 object: list
596
597A slicing selects a range of items in a sequence object (e.g., a string, tuple
598or list). Slicings may be used as expressions or as targets in assignment or
599:keyword:`del` statements. The syntax for a slicing:
600
601.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000602 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000603 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000604 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000605 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000606 lower_bound: `expression`
607 upper_bound: `expression`
608 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000609
610There is ambiguity in the formal syntax here: anything that looks like an
611expression list also looks like a slice list, so any subscription can be
612interpreted as a slicing. Rather than further complicating the syntax, this is
613disambiguated by defining that in this case the interpretation as a subscription
614takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000615slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000616
617.. index::
618 single: start (slice object attribute)
619 single: stop (slice object attribute)
620 single: step (slice object attribute)
621
Georg Brandla4c8c472014-10-31 10:38:49 +0100622The semantics for a slicing are as follows. The primary is indexed (using the
623same :meth:`__getitem__` method as
Georg Brandl96593ed2007-09-07 14:15:41 +0000624normal subscription) with a key that is constructed from the slice list, as
625follows. If the slice list contains at least one comma, the key is a tuple
626containing the conversion of the slice items; otherwise, the conversion of the
627lone slice item is the key. The conversion of a slice item that is an
628expression is that expression. The conversion of a proper slice is a slice
Serhiy Storchaka0d196ed2013-10-09 14:02:31 +0300629object (see section :ref:`types`) whose :attr:`~slice.start`,
630:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
631expressions given as lower bound, upper bound and stride, respectively,
632substituting ``None`` for missing expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000633
634
Chris Jerdonekb4309942012-12-25 14:54:44 -0800635.. index::
636 object: callable
637 single: call
638 single: argument; call semantics
639
Georg Brandl116aa622007-08-15 14:28:22 +0000640.. _calls:
641
642Calls
643-----
644
Chris Jerdonekb4309942012-12-25 14:54:44 -0800645A call calls a callable object (e.g., a :term:`function`) with a possibly empty
646series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000647
648.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000649 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000650 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000651 : ["," "*" `expression`] ["," `keyword_arguments`]
652 : ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000653 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000654 : ["," `keyword_arguments`] ["," "**" `expression`]
655 : | "*" `expression` ["," `keyword_arguments`] ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000656 : | "**" `expression`
657 positional_arguments: `expression` ("," `expression`)*
658 keyword_arguments: `keyword_item` ("," `keyword_item`)*
659 keyword_item: `identifier` "=" `expression`
660
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700661An optional trailing comma may be present after the positional and keyword arguments
662but does not affect the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000663
Chris Jerdonekb4309942012-12-25 14:54:44 -0800664.. index::
665 single: parameter; call semantics
666
Georg Brandl116aa622007-08-15 14:28:22 +0000667The primary must evaluate to a callable object (user-defined functions, built-in
668functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000669instances, and all objects having a :meth:`__call__` method are callable). All
670argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800671to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000672
673.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000674
675If keyword arguments are present, they are first converted to positional
676arguments, as follows. First, a list of unfilled slots is created for the
677formal parameters. If there are N positional arguments, they are placed in the
678first N slots. Next, for each keyword argument, the identifier is used to
679determine the corresponding slot (if the identifier is the same as the first
680formal parameter name, the first slot is used, and so on). If the slot is
681already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
682the argument is placed in the slot, filling it (even if the expression is
683``None``, it fills the slot). When all arguments have been processed, the slots
684that are still unfilled are filled with the corresponding default value from the
685function definition. (Default values are calculated, once, when the function is
686defined; thus, a mutable object such as a list or dictionary used as default
687value will be shared by all calls that don't specify an argument value for the
688corresponding slot; this should usually be avoided.) If there are any unfilled
689slots for which no default value is specified, a :exc:`TypeError` exception is
690raised. Otherwise, the list of filled slots is used as the argument list for
691the call.
692
Georg Brandl495f7b52009-10-27 15:28:25 +0000693.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000694
Georg Brandl495f7b52009-10-27 15:28:25 +0000695 An implementation may provide built-in functions whose positional parameters
696 do not have names, even if they are 'named' for the purpose of documentation,
697 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000698 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000699 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000700
Georg Brandl116aa622007-08-15 14:28:22 +0000701If there are more positional arguments than there are formal parameter slots, a
702:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
703``*identifier`` is present; in this case, that formal parameter receives a tuple
704containing the excess positional arguments (or an empty tuple if there were no
705excess positional arguments).
706
707If any keyword argument does not correspond to a formal parameter name, a
708:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
709``**identifier`` is present; in this case, that formal parameter receives a
710dictionary containing the excess keyword arguments (using the keywords as keys
711and the argument values as corresponding values), or a (new) empty dictionary if
712there were no excess keyword arguments.
713
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300714.. index::
715 single: *; in function calls
716
Georg Brandl116aa622007-08-15 14:28:22 +0000717If the syntax ``*expression`` appears in the function call, ``expression`` must
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300718evaluate to an iterable. Elements from this iterable are treated as if they
719were additional positional arguments; if there are positional arguments
Ezio Melotti59256322011-07-30 21:25:22 +0300720*x1*, ..., *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*,
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300721this is equivalent to a call with M+N positional arguments *x1*, ..., *xN*,
722*y1*, ..., *yM*.
Georg Brandl116aa622007-08-15 14:28:22 +0000723
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000724A consequence of this is that although the ``*expression`` syntax may appear
725*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000726(and the ``**expression`` argument, if any -- see below). So::
727
728 >>> def f(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000729 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000730 ...
731 >>> f(b=1, *(2,))
732 2 1
733 >>> f(a=1, *(2,))
734 Traceback (most recent call last):
735 File "<stdin>", line 1, in ?
736 TypeError: f() got multiple values for keyword argument 'a'
737 >>> f(1, *(2,))
738 1 2
739
740It is unusual for both keyword arguments and the ``*expression`` syntax to be
741used in the same call, so in practice this confusion does not arise.
742
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300743.. index::
744 single: **; in function calls
745
Georg Brandl116aa622007-08-15 14:28:22 +0000746If the syntax ``**expression`` appears in the function call, ``expression`` must
747evaluate to a mapping, the contents of which are treated as additional keyword
748arguments. In the case of a keyword appearing in both ``expression`` and as an
749explicit keyword argument, a :exc:`TypeError` exception is raised.
750
751Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
752used as positional argument slots or as keyword argument names.
753
754A call always returns some value, possibly ``None``, unless it raises an
755exception. How this value is computed depends on the type of the callable
756object.
757
758If it is---
759
760a user-defined function:
761 .. index::
762 pair: function; call
763 triple: user-defined; function; call
764 object: user-defined function
765 object: function
766
767 The code block for the function is executed, passing it the argument list. The
768 first thing the code block will do is bind the formal parameters to the
769 arguments; this is described in section :ref:`function`. When the code block
770 executes a :keyword:`return` statement, this specifies the return value of the
771 function call.
772
773a built-in function or method:
774 .. index::
775 pair: function; call
776 pair: built-in function; call
777 pair: method; call
778 pair: built-in method; call
779 object: built-in method
780 object: built-in function
781 object: method
782 object: function
783
784 The result is up to the interpreter; see :ref:`built-in-funcs` for the
785 descriptions of built-in functions and methods.
786
787a class object:
788 .. index::
789 object: class
790 pair: class object; call
791
792 A new instance of that class is returned.
793
794a class instance method:
795 .. index::
796 object: class instance
797 object: instance
798 pair: class instance; call
799
800 The corresponding user-defined function is called, with an argument list that is
801 one longer than the argument list of the call: the instance becomes the first
802 argument.
803
804a class instance:
805 .. index::
806 pair: instance; call
807 single: __call__() (object method)
808
809 The class must define a :meth:`__call__` method; the effect is then the same as
810 if that method was called.
811
812
813.. _power:
814
815The power operator
816==================
817
818The power operator binds more tightly than unary operators on its left; it binds
819less tightly than unary operators on its right. The syntax is:
820
821.. productionlist::
822 power: `primary` ["**" `u_expr`]
823
824Thus, in an unparenthesized sequence of power and unary operators, the operators
825are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +0000826for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000827
828The power operator has the same semantics as the built-in :func:`pow` function,
829when called with two arguments: it yields its left argument raised to the power
830of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +0000831type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +0000832
Georg Brandl96593ed2007-09-07 14:15:41 +0000833For int operands, the result has the same type as the operands unless the second
834argument is negative; in that case, all arguments are converted to float and a
835float result is delivered. For example, ``10**2`` returns ``100``, but
836``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +0000837
838Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +0000839Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +0000840number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842
843.. _unary:
844
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000845Unary arithmetic and bitwise operations
846=======================================
Georg Brandl116aa622007-08-15 14:28:22 +0000847
848.. index::
849 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +0000850 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000851
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000852All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +0000853
854.. productionlist::
855 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
856
857.. index::
858 single: negation
859 single: minus
860
861The unary ``-`` (minus) operator yields the negation of its numeric argument.
862
863.. index:: single: plus
864
865The unary ``+`` (plus) operator yields its numeric argument unchanged.
866
867.. index:: single: inversion
868
Christian Heimesfaf2f632008-01-06 16:59:19 +0000869
Georg Brandl95817b32008-05-11 14:30:18 +0000870The unary ``~`` (invert) operator yields the bitwise inversion of its integer
871argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
872applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000873
874.. index:: exception: TypeError
875
876In all three cases, if the argument does not have the proper type, a
877:exc:`TypeError` exception is raised.
878
879
880.. _binary:
881
882Binary arithmetic operations
883============================
884
885.. index:: triple: binary; arithmetic; operation
886
887The binary arithmetic operations have the conventional priority levels. Note
888that some of these operations also apply to certain non-numeric types. Apart
889from the power operator, there are only two levels, one for multiplicative
890operators and one for additive operators:
891
892.. productionlist::
Benjamin Petersond51374e2014-04-09 23:55:56 -0400893 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` |
894 : `m_expr` "//" `u_expr`| `m_expr` "/" `u_expr` |
895 : `m_expr` "%" `u_expr`
Georg Brandl116aa622007-08-15 14:28:22 +0000896 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
897
898.. index:: single: multiplication
899
900The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +0000901arguments must either both be numbers, or one argument must be an integer and
902the other must be a sequence. In the former case, the numbers are converted to a
903common type and then multiplied together. In the latter case, sequence
904repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000905
Benjamin Petersond51374e2014-04-09 23:55:56 -0400906.. index:: single: matrix multiplication
907
908The ``@`` (at) operator is intended to be used for matrix multiplication. No
909builtin Python types implement this operator.
910
911.. versionadded:: 3.5
912
Georg Brandl116aa622007-08-15 14:28:22 +0000913.. index::
914 exception: ZeroDivisionError
915 single: division
916
917The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
918their arguments. The numeric arguments are first converted to a common type.
Georg Brandl0aaae262013-10-08 21:47:18 +0200919Division of integers yields a float, while floor division of integers results in an
Georg Brandl96593ed2007-09-07 14:15:41 +0000920integer; the result is that of mathematical division with the 'floor' function
921applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
922exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000923
924.. index:: single: modulo
925
926The ``%`` (modulo) operator yields the remainder from the division of the first
927argument by the second. The numeric arguments are first converted to a common
928type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
929arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
930(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
931result with the same sign as its second operand (or zero); the absolute value of
932the result is strictly smaller than the absolute value of the second operand
933[#]_.
934
Georg Brandl96593ed2007-09-07 14:15:41 +0000935The floor division and modulo operators are connected by the following
936identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
937connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
938x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000939
940In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +0000941also overloaded by string objects to perform old-style string formatting (also
942known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +0000943Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +0000944
945The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +0000946function are not defined for complex numbers. Instead, convert to a floating
947point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +0000948
949.. index:: single: addition
950
Georg Brandl96593ed2007-09-07 14:15:41 +0000951The ``+`` (addition) operator yields the sum of its arguments. The arguments
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700952must either both be numbers or both be sequences of the same type. In the
953former case, the numbers are converted to a common type and then added together.
954In the latter case, the sequences are concatenated.
Georg Brandl116aa622007-08-15 14:28:22 +0000955
956.. index:: single: subtraction
957
958The ``-`` (subtraction) operator yields the difference of its arguments. The
959numeric arguments are first converted to a common type.
960
961
962.. _shifting:
963
964Shifting operations
965===================
966
967.. index:: pair: shifting; operation
968
969The shifting operations have lower priority than the arithmetic operations:
970
971.. productionlist::
972 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
973
Georg Brandl96593ed2007-09-07 14:15:41 +0000974These operators accept integers as arguments. They shift the first argument to
975the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000976
977.. index:: exception: ValueError
978
Georg Brandl0aaae262013-10-08 21:47:18 +0200979A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
980shift by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000981
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000982.. note::
983
984 In the current implementation, the right-hand operand is required
Mark Dickinson505add32010-04-06 18:22:06 +0000985 to be at most :attr:`sys.maxsize`. If the right-hand operand is larger than
986 :attr:`sys.maxsize` an :exc:`OverflowError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000987
988.. _bitwise:
989
Christian Heimesfaf2f632008-01-06 16:59:19 +0000990Binary bitwise operations
991=========================
Georg Brandl116aa622007-08-15 14:28:22 +0000992
Christian Heimesfaf2f632008-01-06 16:59:19 +0000993.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000994
995Each of the three bitwise operations has a different priority level:
996
997.. productionlist::
998 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
999 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1000 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1001
Christian Heimesfaf2f632008-01-06 16:59:19 +00001002.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +00001003
Georg Brandl96593ed2007-09-07 14:15:41 +00001004The ``&`` operator yields the bitwise AND of its arguments, which must be
1005integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001006
1007.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001008 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001009 pair: exclusive; or
1010
1011The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001012must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001013
1014.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001015 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001016 pair: inclusive; or
1017
1018The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001019must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001020
1021
1022.. _comparisons:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001023.. _is:
Georg Brandl375aec22011-01-15 17:03:02 +00001024.. _is not:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001025.. _in:
Georg Brandl375aec22011-01-15 17:03:02 +00001026.. _not in:
Georg Brandl116aa622007-08-15 14:28:22 +00001027
1028Comparisons
1029===========
1030
1031.. index:: single: comparison
1032
1033.. index:: pair: C; language
1034
1035Unlike C, all comparison operations in Python have the same priority, which is
1036lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1037C, expressions like ``a < b < c`` have the interpretation that is conventional
1038in mathematics:
1039
1040.. productionlist::
1041 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1042 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1043 : | "is" ["not"] | ["not"] "in"
1044
1045Comparisons yield boolean values: ``True`` or ``False``.
1046
1047.. index:: pair: chaining; comparisons
1048
1049Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1050``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1051cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1052
Guido van Rossum04110fb2007-08-24 16:32:05 +00001053Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1054*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1055to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1056evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001057
Guido van Rossum04110fb2007-08-24 16:32:05 +00001058Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001059*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1060pretty).
1061
1062The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1063values of two objects. The objects need not have the same type. If both are
Georg Brandl9609cea2008-09-09 19:31:57 +00001064numbers, they are converted to a common type. Otherwise, the ``==`` and ``!=``
1065operators *always* consider objects of different types to be unequal, while the
1066``<``, ``>``, ``>=`` and ``<=`` operators raise a :exc:`TypeError` when
1067comparing objects of different types that do not implement these operators for
1068the given pair of types. You can control comparison behavior of objects of
Georg Brandl22b34312009-07-26 14:54:51 +00001069non-built-in types by defining rich comparison methods like :meth:`__gt__`,
Georg Brandl9609cea2008-09-09 19:31:57 +00001070described in section :ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001071
1072Comparison of objects of the same type depends on the type:
1073
1074* Numbers are compared arithmetically.
1075
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001076* The values :const:`float('NaN')` and :const:`Decimal('NaN')` are special.
1077 The are identical to themselves, ``x is x`` but are not equal to themselves,
1078 ``x != x``. Additionally, comparing any value to a not-a-number value
1079 will return ``False``. For example, both ``3 < float('NaN')`` and
1080 ``float('NaN') < 3`` will return ``False``.
1081
Georg Brandl96593ed2007-09-07 14:15:41 +00001082* Bytes objects are compared lexicographically using the numeric values of their
1083 elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001084
Georg Brandl116aa622007-08-15 14:28:22 +00001085* Strings are compared lexicographically using the numeric equivalents (the
Georg Brandl96593ed2007-09-07 14:15:41 +00001086 result of the built-in function :func:`ord`) of their characters. [#]_ String
1087 and bytes object can't be compared!
Georg Brandl116aa622007-08-15 14:28:22 +00001088
1089* Tuples and lists are compared lexicographically using comparison of
1090 corresponding elements. This means that to compare equal, each element must
1091 compare equal and the two sequences must be of the same type and have the same
1092 length.
1093
1094 If not equal, the sequences are ordered the same as their first differing
Mark Dickinsonc48d8342009-02-01 14:18:10 +00001095 elements. For example, ``[1,2,x] <= [1,2,y]`` has the same value as
1096 ``x <= y``. If the corresponding element does not exist, the shorter
Georg Brandl96593ed2007-09-07 14:15:41 +00001097 sequence is ordered first (for example, ``[1,2] < [1,2,3]``).
Georg Brandl116aa622007-08-15 14:28:22 +00001098
Senthil Kumaran07367672010-07-14 20:30:02 +00001099* Mappings (dictionaries) compare equal if and only if they have the same
1100 ``(key, value)`` pairs. Order comparisons ``('<', '<=', '>=', '>')``
1101 raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001102
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001103* Sets and frozensets define comparison operators to mean subset and superset
1104 tests. Those relations do not define total orderings (the two sets ``{1,2}``
1105 and {2,3} are not equal, nor subsets of one another, nor supersets of one
1106 another). Accordingly, sets are not appropriate arguments for functions
1107 which depend on total ordering. For example, :func:`min`, :func:`max`, and
1108 :func:`sorted` produce undefined results given a list of sets as inputs.
1109
Georg Brandl22b34312009-07-26 14:54:51 +00001110* Most other objects of built-in types compare unequal unless they are the same
Georg Brandl116aa622007-08-15 14:28:22 +00001111 object; the choice whether one object is considered smaller or larger than
1112 another one is made arbitrarily but consistently within one execution of a
1113 program.
1114
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001115Comparison of objects of differing types depends on whether either of the
Georg Brandl7ea9a422012-10-06 13:48:39 +02001116types provide explicit support for the comparison. Most numeric types can be
1117compared with one another. When cross-type comparison is not supported, the
1118comparison method returns ``NotImplemented``.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001119
Georg Brandl495f7b52009-10-27 15:28:25 +00001120.. _membership-test-details:
1121
Georg Brandl96593ed2007-09-07 14:15:41 +00001122The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
1123s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not
1124in s`` returns the negation of ``x in s``. All built-in sequences and set types
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001125support this as well as dictionary, for which :keyword:`in` tests whether the
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001126dictionary has a given key. For container types such as list, tuple, set,
Raymond Hettinger0cc818f2008-11-21 10:40:51 +00001127frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001128to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001129
Georg Brandl4b491312007-08-31 09:22:56 +00001130For the string and bytes types, ``x in y`` is true if and only if *x* is a
1131substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1132always considered to be a substring of any other string, so ``"" in "abc"`` will
1133return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001134
Georg Brandl116aa622007-08-15 14:28:22 +00001135For user-defined classes which define the :meth:`__contains__` method, ``x in
1136y`` is true if and only if ``y.__contains__(x)`` is true.
1137
Georg Brandl495f7b52009-10-27 15:28:25 +00001138For user-defined classes which do not define :meth:`__contains__` but do define
1139:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1140produced while iterating over ``y``. If an exception is raised during the
1141iteration, it is as if :keyword:`in` raised that exception.
1142
1143Lastly, the old-style iteration protocol is tried: if a class defines
Georg Brandl116aa622007-08-15 14:28:22 +00001144:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1145integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001146raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001147if :keyword:`in` raised that exception).
1148
1149.. index::
1150 operator: in
1151 operator: not in
1152 pair: membership; test
1153 object: sequence
1154
1155The operator :keyword:`not in` is defined to have the inverse true value of
1156:keyword:`in`.
1157
1158.. index::
1159 operator: is
1160 operator: is not
1161 pair: identity; test
1162
1163The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1164is 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 +00001165yields the inverse truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001166
1167
1168.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001169.. _and:
1170.. _or:
1171.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001172
1173Boolean operations
1174==================
1175
1176.. index::
1177 pair: Conditional; expression
1178 pair: Boolean; operation
1179
Georg Brandl116aa622007-08-15 14:28:22 +00001180.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001181 or_test: `and_test` | `or_test` "or" `and_test`
1182 and_test: `not_test` | `and_test` "and" `not_test`
1183 not_test: `comparison` | "not" `not_test`
1184
1185In the context of Boolean operations, and also when expressions are used by
1186control flow statements, the following values are interpreted as false:
1187``False``, ``None``, numeric zero of all types, and empty strings and containers
1188(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001189other values are interpreted as true. User-defined objects can customize their
1190truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001191
1192.. index:: operator: not
1193
1194The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1195otherwise.
1196
Georg Brandl116aa622007-08-15 14:28:22 +00001197.. index:: operator: and
1198
1199The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1200returned; otherwise, *y* is evaluated and the resulting value is returned.
1201
1202.. index:: operator: or
1203
1204The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1205returned; otherwise, *y* is evaluated and the resulting value is returned.
1206
1207(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1208they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001209argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001210replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001211the desired value. Because :keyword:`not` has to create a new value, it
1212returns a boolean value regardless of the type of its argument
1213(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001214
1215
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001216Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001217=======================
1218
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001219.. index::
1220 pair: conditional; expression
1221 pair: ternary; operator
1222
1223.. productionlist::
1224 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
Georg Brandl242e6a02013-10-06 10:28:39 +02001225 expression: `conditional_expression` | `lambda_expr`
1226 expression_nocond: `or_test` | `lambda_expr_nocond`
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001227
1228Conditional expressions (sometimes called a "ternary operator") have the lowest
1229priority of all Python operations.
1230
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001231The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*.
1232If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001233evaluated and its value is returned.
1234
1235See :pep:`308` for more details about conditional expressions.
1236
1237
Georg Brandl116aa622007-08-15 14:28:22 +00001238.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001239.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001240
1241Lambdas
1242=======
1243
1244.. index::
1245 pair: lambda; expression
1246 pair: lambda; form
1247 pair: anonymous; function
1248
1249.. productionlist::
Georg Brandl242e6a02013-10-06 10:28:39 +02001250 lambda_expr: "lambda" [`parameter_list`]: `expression`
1251 lambda_expr_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001252
Zachary Ware2f78b842014-06-03 09:32:40 -05001253Lambda expressions (sometimes called lambda forms) are used to create anonymous
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001254functions. The expression ``lambda arguments: expression`` yields a function
1255object. The unnamed object behaves like a function object defined with ::
Georg Brandl116aa622007-08-15 14:28:22 +00001256
Georg Brandl96593ed2007-09-07 14:15:41 +00001257 def <lambda>(arguments):
Georg Brandl116aa622007-08-15 14:28:22 +00001258 return expression
1259
1260See section :ref:`function` for the syntax of parameter lists. Note that
Georg Brandl242e6a02013-10-06 10:28:39 +02001261functions created with lambda expressions cannot contain statements or
1262annotations.
Georg Brandl116aa622007-08-15 14:28:22 +00001263
Georg Brandl116aa622007-08-15 14:28:22 +00001264
1265.. _exprlists:
1266
1267Expression lists
1268================
1269
1270.. index:: pair: expression; list
1271
1272.. productionlist::
1273 expression_list: `expression` ( "," `expression` )* [","]
1274
1275.. index:: object: tuple
1276
1277An expression list containing at least one comma yields a tuple. The length of
1278the tuple is the number of expressions in the list. The expressions are
1279evaluated from left to right.
1280
1281.. index:: pair: trailing; comma
1282
1283The trailing comma is required only to create a single tuple (a.k.a. a
1284*singleton*); it is optional in all other cases. A single expression without a
1285trailing comma doesn't create a tuple, but rather yields the value of that
1286expression. (To create an empty tuple, use an empty pair of parentheses:
1287``()``.)
1288
1289
1290.. _evalorder:
1291
1292Evaluation order
1293================
1294
1295.. index:: pair: evaluation; order
1296
Georg Brandl96593ed2007-09-07 14:15:41 +00001297Python evaluates expressions from left to right. Notice that while evaluating
1298an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001299
1300In the following lines, expressions will be evaluated in the arithmetic order of
1301their suffixes::
1302
1303 expr1, expr2, expr3, expr4
1304 (expr1, expr2, expr3, expr4)
1305 {expr1: expr2, expr3: expr4}
1306 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001307 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001308 expr3, expr4 = expr1, expr2
1309
1310
1311.. _operator-summary:
1312
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001313Operator precedence
1314===================
Georg Brandl116aa622007-08-15 14:28:22 +00001315
1316.. index:: pair: operator; precedence
1317
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001318The following table summarizes the operator precedence in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001319precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001320the same box have the same precedence. Unless the syntax is explicitly given,
1321operators are binary. Operators in the same box group left to right (except for
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001322exponentiation, which groups from right to left).
1323
1324Note that comparisons, membership tests, and identity tests, all have the same
1325precedence and have a left-to-right chaining feature as described in the
1326:ref:`comparisons` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001327
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001328
1329+-----------------------------------------------+-------------------------------------+
1330| Operator | Description |
1331+===============================================+=====================================+
1332| :keyword:`lambda` | Lambda expression |
1333+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001334| :keyword:`if` -- :keyword:`else` | Conditional expression |
1335+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001336| :keyword:`or` | Boolean OR |
1337+-----------------------------------------------+-------------------------------------+
1338| :keyword:`and` | Boolean AND |
1339+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001340| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001341+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001342| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001343| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001344| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001345+-----------------------------------------------+-------------------------------------+
1346| ``|`` | Bitwise OR |
1347+-----------------------------------------------+-------------------------------------+
1348| ``^`` | Bitwise XOR |
1349+-----------------------------------------------+-------------------------------------+
1350| ``&`` | Bitwise AND |
1351+-----------------------------------------------+-------------------------------------+
1352| ``<<``, ``>>`` | Shifts |
1353+-----------------------------------------------+-------------------------------------+
1354| ``+``, ``-`` | Addition and subtraction |
1355+-----------------------------------------------+-------------------------------------+
Benjamin Petersond51374e2014-04-09 23:55:56 -04001356| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix |
1357| | multiplication division, |
1358| | remainder [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001359+-----------------------------------------------+-------------------------------------+
1360| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1361+-----------------------------------------------+-------------------------------------+
1362| ``**`` | Exponentiation [#]_ |
1363+-----------------------------------------------+-------------------------------------+
1364| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1365| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1366+-----------------------------------------------+-------------------------------------+
1367| ``(expressions...)``, | Binding or tuple display, |
1368| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001369| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001370| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001371+-----------------------------------------------+-------------------------------------+
1372
Georg Brandl116aa622007-08-15 14:28:22 +00001373
1374.. rubric:: Footnotes
1375
Georg Brandl116aa622007-08-15 14:28:22 +00001376.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1377 true numerically due to roundoff. For example, and assuming a platform on which
1378 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1379 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001380 1e100``, which is numerically exactly equal to ``1e100``. The function
1381 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001382 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1383 is more appropriate depends on the application.
1384
1385.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001386 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001387 cases, Python returns the latter result, in order to preserve that
1388 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1389
Georg Brandl96593ed2007-09-07 14:15:41 +00001390.. [#] While comparisons between strings make sense at the byte level, they may
1391 be counter-intuitive to users. For example, the strings ``"\u00C7"`` and
1392 ``"\u0327\u0043"`` compare differently, even though they both represent the
Georg Brandlae2dbe22009-03-13 19:04:40 +00001393 same unicode character (LATIN CAPITAL LETTER C WITH CEDILLA). To compare
Georg Brandl9afde1c2007-11-01 20:32:30 +00001394 strings in a human recognizable way, compare using
1395 :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001396
Georg Brandl48310cd2009-01-03 21:18:54 +00001397.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001398 descriptors, you may notice seemingly unusual behaviour in certain uses of
1399 the :keyword:`is` operator, like those involving comparisons between instance
1400 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001401
Georg Brandl063f2372010-12-01 15:32:43 +00001402.. [#] The ``%`` operator is also used for string formatting; the same
1403 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001404
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001405.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1406 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.