blob: 364135a107cb79a54d8e492026bfb82d963354a7 [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
32implementation for built-in types works that way:
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
41Some additional rules apply for certain operators (e.g., a string left argument
Georg Brandl96593ed2007-09-07 14:15:41 +000042to the '%' operator). Extensions must define their own conversion behavior.
Georg Brandl116aa622007-08-15 14:28:22 +000043
44
45.. _atoms:
46
47Atoms
48=====
49
Georg Brandl96593ed2007-09-07 14:15:41 +000050.. index:: atom
Georg Brandl116aa622007-08-15 14:28:22 +000051
52Atoms are the most basic elements of expressions. The simplest atoms are
Georg Brandl96593ed2007-09-07 14:15:41 +000053identifiers or literals. Forms enclosed in parentheses, brackets or braces are
54also categorized syntactically as atoms. The syntax for atoms is:
Georg Brandl116aa622007-08-15 14:28:22 +000055
56.. productionlist::
57 atom: `identifier` | `literal` | `enclosure`
Georg Brandl96593ed2007-09-07 14:15:41 +000058 enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display`
59 : | `generator_expression` | `yield_atom`
Georg Brandl116aa622007-08-15 14:28:22 +000060
61
62.. _atom-identifiers:
63
64Identifiers (Names)
65-------------------
66
Georg Brandl96593ed2007-09-07 14:15:41 +000067.. index:: name, identifier
Georg Brandl116aa622007-08-15 14:28:22 +000068
69An identifier occurring as an atom is a name. See section :ref:`identifiers`
70for lexical definition and section :ref:`naming` for documentation of naming and
71binding.
72
73.. index:: exception: NameError
74
75When the name is bound to an object, evaluation of the atom yields that object.
76When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
77exception.
78
79.. index::
80 pair: name; mangling
81 pair: private; names
82
83**Private name mangling:** When an identifier that textually occurs in a class
84definition begins with two or more underscore characters and does not end in two
85or more underscores, it is considered a :dfn:`private name` of that class.
86Private names are transformed to a longer form before code is generated for
87them. The transformation inserts the class name in front of the name, with
88leading underscores removed, and a single underscore inserted in front of the
89class name. For example, the identifier ``__spam`` occurring in a class named
90``Ham`` will be transformed to ``_Ham__spam``. This transformation is
91independent of the syntactical context in which the identifier is used. If the
92transformed name is extremely long (longer than 255 characters), implementation
93defined truncation may happen. If the class name consists only of underscores,
94no transformation is done.
95
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
187to in the target list don't "leak" in the enclosing scope.
188
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
297:meth:`__next__` method is called for generator object (in the same fashion as
298normal generators). However, the leftmost :keyword:`for` clause is immediately
299evaluated, so that an error produced by it can be seen before any other possible
300error in the code that handles the generator expression. Subsequent
301:keyword:`for` clauses cannot be evaluated immediately since they may depend on
302the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y
303in bar(x))``.
304
305The parentheses can be omitted on calls with only one argument. See section
306:ref:`calls` for the detail.
307
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
Georg Brandl116aa622007-08-15 14:28:22 +0000323The :keyword:`yield` expression is only used when defining a generator function,
Georg Brandl96593ed2007-09-07 14:15:41 +0000324and can only be used in the body of a function definition. Using a
Georg Brandl116aa622007-08-15 14:28:22 +0000325:keyword:`yield` expression in a function definition is sufficient to cause that
326definition to create a generator function instead of a normal function.
327
328When a generator function is called, it returns an iterator known as a
329generator. That generator then controls the execution of a generator function.
330The execution starts when one of the generator's methods is called. At that
331time, the execution proceeds to the first :keyword:`yield` expression, where it
332is suspended again, returning the value of :token:`expression_list` to
333generator's caller. By suspended we mean that all local state is retained,
334including the current bindings of local variables, the instruction pointer, and
335the internal evaluation stack. When the execution is resumed by calling one of
336the generator's methods, the function can proceed exactly as if the
Georg Brandl96593ed2007-09-07 14:15:41 +0000337:keyword:`yield` expression was just another external call. The value of the
Georg Brandl116aa622007-08-15 14:28:22 +0000338:keyword:`yield` expression after resuming depends on the method which resumed
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000339the execution. If :meth:`__next__` is used (typically via either a
340:keyword:`for` or the :func:`next` builtin) then the result is :const:`None`,
341otherwise, if :meth:`send` is used, then the result will be the value passed
342in to that 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
349where should the execution 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
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000352:keyword:`yield` expressions are allowed in the :keyword:`try` clause of a
Georg Brandl02c30562007-09-07 17:52:53 +0000353:keyword:`try` ... :keyword:`finally` construct. If the generator is not
354resumed before it is finalized (by reaching a zero reference count or by being
355garbage collected), the generator-iterator's :meth:`close` method will be
356called, allowing any pending :keyword:`finally` clauses to execute.
357
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
361:meth:`send` and any exceptions passed in with :meth:`throw` are passed to
362the underlying iterator if it has the appropriate methods. If this is not the
363case, then :meth:`send` will raise :exc:`AttributeError` or :exc:`TypeError`,
364while :meth:`throw` will just raise the passed in exception immediately.
365
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
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000375The parentheses can be omitted when the :keyword:`yield` expression is the
376sole expression on the right hand side of an assignment statement.
377
Georg Brandl116aa622007-08-15 14:28:22 +0000378.. index:: object: generator
379
R David Murray2c1d1d62012-08-17 20:48:59 -0400380
381Generator-iterator methods
382^^^^^^^^^^^^^^^^^^^^^^^^^^
383
384This subsection describes the methods of a generator iterator. They can
385be used to control the execution of a generator function.
386
387Note that calling any of the generator methods below when the generator
388is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390.. index:: exception: StopIteration
391
392
Georg Brandl96593ed2007-09-07 14:15:41 +0000393.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000394
Georg Brandl96593ed2007-09-07 14:15:41 +0000395 Starts the execution of a generator function or resumes it at the last
396 executed :keyword:`yield` expression. When a generator function is resumed
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000397 with a :meth:`__next__` method, the current :keyword:`yield` expression
398 always evaluates to :const:`None`. The execution then continues to the next
Georg Brandl96593ed2007-09-07 14:15:41 +0000399 :keyword:`yield` expression, where the generator is suspended again, and the
400 value of the :token:`expression_list` is returned to :meth:`next`'s caller.
401 If the generator exits without yielding another value, a :exc:`StopIteration`
402 exception is raised.
403
404 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
405 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407
408.. method:: generator.send(value)
409
410 Resumes the execution and "sends" a value into the generator function. The
411 ``value`` argument becomes the result of the current :keyword:`yield`
412 expression. The :meth:`send` method returns the next value yielded by the
413 generator, or raises :exc:`StopIteration` if the generator exits without
Georg Brandl96593ed2007-09-07 14:15:41 +0000414 yielding another value. When :meth:`send` is called to start the generator,
415 it must be called with :const:`None` as the argument, because there is no
Christian Heimesc3f30c42008-02-22 16:37:40 +0000416 :keyword:`yield` expression that could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418
419.. method:: generator.throw(type[, value[, traceback]])
420
421 Raises an exception of type ``type`` at the point where generator was paused,
422 and returns the next value yielded by the generator function. If the generator
423 exits without yielding another value, a :exc:`StopIteration` exception is
424 raised. If the generator function does not catch the passed-in exception, or
425 raises a different exception, then that exception propagates to the caller.
426
427.. index:: exception: GeneratorExit
428
429
430.. method:: generator.close()
431
432 Raises a :exc:`GeneratorExit` at the point where the generator function was
Georg Brandl96593ed2007-09-07 14:15:41 +0000433 paused. If the generator function then raises :exc:`StopIteration` (by
434 exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by
435 not catching the exception), close returns to its caller. If the generator
436 yields a value, a :exc:`RuntimeError` is raised. If the generator raises any
437 other exception, it is propagated to the caller. :meth:`close` does nothing
438 if the generator has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000439
440Here is a simple example that demonstrates the behavior of generators and
441generator functions::
442
443 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000444 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000445 ... try:
446 ... while True:
447 ... try:
448 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000449 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000450 ... value = e
451 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000452 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000453 ...
454 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000455 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000456 Execution starts when 'next()' is called for the first time.
457 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000458 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000459 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000460 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000461 2
462 >>> generator.throw(TypeError, "spam")
463 TypeError('spam',)
464 >>> generator.close()
465 Don't forget to clean up when 'close()' is called.
466
467
468.. seealso::
469
Georg Brandl02c30562007-09-07 17:52:53 +0000470 :pep:`0255` - Simple Generators
471 The proposal for adding generators and the :keyword:`yield` statement to Python.
472
Georg Brandl116aa622007-08-15 14:28:22 +0000473 :pep:`0342` - Coroutines via Enhanced Generators
Georg Brandl96593ed2007-09-07 14:15:41 +0000474 The proposal to enhance the API and syntax of generators, making them
475 usable as simple coroutines.
Georg Brandl116aa622007-08-15 14:28:22 +0000476
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000477 :pep:`0380` - Syntax for Delegating to a Subgenerator
478 The proposal to introduce the :token:`yield_from` syntax, making delegation
479 to sub-generators easy.
480
Georg Brandl116aa622007-08-15 14:28:22 +0000481
482.. _primaries:
483
484Primaries
485=========
486
487.. index:: single: primary
488
489Primaries represent the most tightly bound operations of the language. Their
490syntax is:
491
492.. productionlist::
493 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
494
495
496.. _attribute-references:
497
498Attribute references
499--------------------
500
501.. index:: pair: attribute; reference
502
503An attribute reference is a primary followed by a period and a name:
504
505.. productionlist::
506 attributeref: `primary` "." `identifier`
507
508.. index::
509 exception: AttributeError
510 object: module
511 object: list
512
513The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000514references, which most objects do. This object is then asked to produce the
515attribute whose name is the identifier (which can be customized by overriding
516the :meth:`__getattr__` method). If this attribute is not available, the
517exception :exc:`AttributeError` is raised. Otherwise, the type and value of the
518object produced is determined by the object. Multiple evaluations of the same
519attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521
522.. _subscriptions:
523
524Subscriptions
525-------------
526
527.. index:: single: subscription
528
529.. index::
530 object: sequence
531 object: mapping
532 object: string
533 object: tuple
534 object: list
535 object: dictionary
536 pair: sequence; item
537
538A subscription selects an item of a sequence (string, tuple or list) or mapping
539(dictionary) object:
540
541.. productionlist::
542 subscription: `primary` "[" `expression_list` "]"
543
Georg Brandl96593ed2007-09-07 14:15:41 +0000544The primary must evaluate to an object that supports subscription, e.g. a list
545or dictionary. User-defined objects can support subscription by defining a
546:meth:`__getitem__` method.
547
548For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000549
550If the primary is a mapping, the expression list must evaluate to an object
551whose value is one of the keys of the mapping, and the subscription selects the
552value in the mapping that corresponds to that key. (The expression list is a
553tuple except if it has exactly one item.)
554
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000555If the primary is a sequence, the expression (list) must evaluate to an integer
556or a slice (as discussed in the following section).
557
558The formal syntax makes no special provision for negative indices in
559sequences; however, built-in sequences all provide a :meth:`__getitem__`
560method that interprets negative indices by adding the length of the sequence
561to the index (so that ``x[-1]`` selects the last item of ``x``). The
562resulting value must be a nonnegative integer less than the number of items in
563the sequence, and the subscription selects the item whose index is that value
564(counting from zero). Since the support for negative indices and slicing
565occurs in the object's :meth:`__getitem__` method, subclasses overriding
566this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000567
568.. index::
569 single: character
570 pair: string; item
571
572A string's items are characters. A character is not a separate data type but a
573string of exactly one character.
574
575
576.. _slicings:
577
578Slicings
579--------
580
581.. index::
582 single: slicing
583 single: slice
584
585.. index::
586 object: sequence
587 object: string
588 object: tuple
589 object: list
590
591A slicing selects a range of items in a sequence object (e.g., a string, tuple
592or list). Slicings may be used as expressions or as targets in assignment or
593:keyword:`del` statements. The syntax for a slicing:
594
595.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000596 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000597 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000598 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000599 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000600 lower_bound: `expression`
601 upper_bound: `expression`
602 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000603
604There is ambiguity in the formal syntax here: anything that looks like an
605expression list also looks like a slice list, so any subscription can be
606interpreted as a slicing. Rather than further complicating the syntax, this is
607disambiguated by defining that in this case the interpretation as a subscription
608takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000609slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000610
611.. index::
612 single: start (slice object attribute)
613 single: stop (slice object attribute)
614 single: step (slice object attribute)
615
Thomas Wouters53de1902007-09-04 09:03:59 +0000616The semantics for a slicing are as follows. The primary must evaluate to a
Georg Brandl96593ed2007-09-07 14:15:41 +0000617mapping object, and it is indexed (using the same :meth:`__getitem__` method as
618normal subscription) with a key that is constructed from the slice list, as
619follows. If the slice list contains at least one comma, the key is a tuple
620containing the conversion of the slice items; otherwise, the conversion of the
621lone slice item is the key. The conversion of a slice item that is an
622expression is that expression. The conversion of a proper slice is a slice
623object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
624:attr:`step` attributes are the values of the expressions given as lower bound,
625upper bound and stride, respectively, substituting ``None`` for missing
626expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000627
628
629.. _calls:
630
631Calls
632-----
633
634.. index:: single: call
635
636.. index:: object: callable
637
638A call calls a callable object (e.g., a function) with a possibly empty series
639of arguments:
640
641.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000642 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000643 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000644 : ["," "*" `expression`] ["," `keyword_arguments`]
645 : ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000646 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000647 : ["," `keyword_arguments`] ["," "**" `expression`]
648 : | "*" `expression` ["," `keyword_arguments`] ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000649 : | "**" `expression`
650 positional_arguments: `expression` ("," `expression`)*
651 keyword_arguments: `keyword_item` ("," `keyword_item`)*
652 keyword_item: `identifier` "=" `expression`
653
654A trailing comma may be present after the positional and keyword arguments but
655does not affect the semantics.
656
657The primary must evaluate to a callable object (user-defined functions, built-in
658functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000659instances, and all objects having a :meth:`__call__` method are callable). All
660argument expressions are evaluated before the call is attempted. Please refer
661to section :ref:`function` for the syntax of formal parameter lists.
662
663.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000664
665If keyword arguments are present, they are first converted to positional
666arguments, as follows. First, a list of unfilled slots is created for the
667formal parameters. If there are N positional arguments, they are placed in the
668first N slots. Next, for each keyword argument, the identifier is used to
669determine the corresponding slot (if the identifier is the same as the first
670formal parameter name, the first slot is used, and so on). If the slot is
671already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
672the argument is placed in the slot, filling it (even if the expression is
673``None``, it fills the slot). When all arguments have been processed, the slots
674that are still unfilled are filled with the corresponding default value from the
675function definition. (Default values are calculated, once, when the function is
676defined; thus, a mutable object such as a list or dictionary used as default
677value will be shared by all calls that don't specify an argument value for the
678corresponding slot; this should usually be avoided.) If there are any unfilled
679slots for which no default value is specified, a :exc:`TypeError` exception is
680raised. Otherwise, the list of filled slots is used as the argument list for
681the call.
682
Georg Brandl495f7b52009-10-27 15:28:25 +0000683.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000684
Georg Brandl495f7b52009-10-27 15:28:25 +0000685 An implementation may provide built-in functions whose positional parameters
686 do not have names, even if they are 'named' for the purpose of documentation,
687 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000688 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000689 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000690
Georg Brandl116aa622007-08-15 14:28:22 +0000691If there are more positional arguments than there are formal parameter slots, a
692:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
693``*identifier`` is present; in this case, that formal parameter receives a tuple
694containing the excess positional arguments (or an empty tuple if there were no
695excess positional arguments).
696
697If any keyword argument does not correspond to a formal parameter name, a
698:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
699``**identifier`` is present; in this case, that formal parameter receives a
700dictionary containing the excess keyword arguments (using the keywords as keys
701and the argument values as corresponding values), or a (new) empty dictionary if
702there were no excess keyword arguments.
703
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300704.. index::
705 single: *; in function calls
706
Georg Brandl116aa622007-08-15 14:28:22 +0000707If the syntax ``*expression`` appears in the function call, ``expression`` must
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300708evaluate to an iterable. Elements from this iterable are treated as if they
709were additional positional arguments; if there are positional arguments
Ezio Melotti59256322011-07-30 21:25:22 +0300710*x1*, ..., *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*,
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300711this is equivalent to a call with M+N positional arguments *x1*, ..., *xN*,
712*y1*, ..., *yM*.
Georg Brandl116aa622007-08-15 14:28:22 +0000713
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000714A consequence of this is that although the ``*expression`` syntax may appear
715*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000716(and the ``**expression`` argument, if any -- see below). So::
717
718 >>> def f(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000719 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000720 ...
721 >>> f(b=1, *(2,))
722 2 1
723 >>> f(a=1, *(2,))
724 Traceback (most recent call last):
725 File "<stdin>", line 1, in ?
726 TypeError: f() got multiple values for keyword argument 'a'
727 >>> f(1, *(2,))
728 1 2
729
730It is unusual for both keyword arguments and the ``*expression`` syntax to be
731used in the same call, so in practice this confusion does not arise.
732
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300733.. index::
734 single: **; in function calls
735
Georg Brandl116aa622007-08-15 14:28:22 +0000736If the syntax ``**expression`` appears in the function call, ``expression`` must
737evaluate to a mapping, the contents of which are treated as additional keyword
738arguments. In the case of a keyword appearing in both ``expression`` and as an
739explicit keyword argument, a :exc:`TypeError` exception is raised.
740
741Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
742used as positional argument slots or as keyword argument names.
743
744A call always returns some value, possibly ``None``, unless it raises an
745exception. How this value is computed depends on the type of the callable
746object.
747
748If it is---
749
750a user-defined function:
751 .. index::
752 pair: function; call
753 triple: user-defined; function; call
754 object: user-defined function
755 object: function
756
757 The code block for the function is executed, passing it the argument list. The
758 first thing the code block will do is bind the formal parameters to the
759 arguments; this is described in section :ref:`function`. When the code block
760 executes a :keyword:`return` statement, this specifies the return value of the
761 function call.
762
763a built-in function or method:
764 .. index::
765 pair: function; call
766 pair: built-in function; call
767 pair: method; call
768 pair: built-in method; call
769 object: built-in method
770 object: built-in function
771 object: method
772 object: function
773
774 The result is up to the interpreter; see :ref:`built-in-funcs` for the
775 descriptions of built-in functions and methods.
776
777a class object:
778 .. index::
779 object: class
780 pair: class object; call
781
782 A new instance of that class is returned.
783
784a class instance method:
785 .. index::
786 object: class instance
787 object: instance
788 pair: class instance; call
789
790 The corresponding user-defined function is called, with an argument list that is
791 one longer than the argument list of the call: the instance becomes the first
792 argument.
793
794a class instance:
795 .. index::
796 pair: instance; call
797 single: __call__() (object method)
798
799 The class must define a :meth:`__call__` method; the effect is then the same as
800 if that method was called.
801
802
803.. _power:
804
805The power operator
806==================
807
808The power operator binds more tightly than unary operators on its left; it binds
809less tightly than unary operators on its right. The syntax is:
810
811.. productionlist::
812 power: `primary` ["**" `u_expr`]
813
814Thus, in an unparenthesized sequence of power and unary operators, the operators
815are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +0000816for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000817
818The power operator has the same semantics as the built-in :func:`pow` function,
819when called with two arguments: it yields its left argument raised to the power
820of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +0000821type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +0000822
Georg Brandl96593ed2007-09-07 14:15:41 +0000823For int operands, the result has the same type as the operands unless the second
824argument is negative; in that case, all arguments are converted to float and a
825float result is delivered. For example, ``10**2`` returns ``100``, but
826``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +0000827
828Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +0000829Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +0000830number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000831
832
833.. _unary:
834
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000835Unary arithmetic and bitwise operations
836=======================================
Georg Brandl116aa622007-08-15 14:28:22 +0000837
838.. index::
839 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +0000840 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000841
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000842All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +0000843
844.. productionlist::
845 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
846
847.. index::
848 single: negation
849 single: minus
850
851The unary ``-`` (minus) operator yields the negation of its numeric argument.
852
853.. index:: single: plus
854
855The unary ``+`` (plus) operator yields its numeric argument unchanged.
856
857.. index:: single: inversion
858
Christian Heimesfaf2f632008-01-06 16:59:19 +0000859
Georg Brandl95817b32008-05-11 14:30:18 +0000860The unary ``~`` (invert) operator yields the bitwise inversion of its integer
861argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
862applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000863
864.. index:: exception: TypeError
865
866In all three cases, if the argument does not have the proper type, a
867:exc:`TypeError` exception is raised.
868
869
870.. _binary:
871
872Binary arithmetic operations
873============================
874
875.. index:: triple: binary; arithmetic; operation
876
877The binary arithmetic operations have the conventional priority levels. Note
878that some of these operations also apply to certain non-numeric types. Apart
879from the power operator, there are only two levels, one for multiplicative
880operators and one for additive operators:
881
882.. productionlist::
883 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
884 : | `m_expr` "%" `u_expr`
885 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
886
887.. index:: single: multiplication
888
889The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +0000890arguments must either both be numbers, or one argument must be an integer and
891the other must be a sequence. In the former case, the numbers are converted to a
892common type and then multiplied together. In the latter case, sequence
893repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000894
895.. index::
896 exception: ZeroDivisionError
897 single: division
898
899The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
900their arguments. The numeric arguments are first converted to a common type.
Georg Brandl96593ed2007-09-07 14:15:41 +0000901Integer division yields a float, while floor division of integers results in an
902integer; the result is that of mathematical division with the 'floor' function
903applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
904exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000905
906.. index:: single: modulo
907
908The ``%`` (modulo) operator yields the remainder from the division of the first
909argument by the second. The numeric arguments are first converted to a common
910type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
911arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
912(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
913result with the same sign as its second operand (or zero); the absolute value of
914the result is strictly smaller than the absolute value of the second operand
915[#]_.
916
Georg Brandl96593ed2007-09-07 14:15:41 +0000917The floor division and modulo operators are connected by the following
918identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
919connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
920x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000921
922In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +0000923also overloaded by string objects to perform old-style string formatting (also
924known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +0000925Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +0000926
927The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +0000928function are not defined for complex numbers. Instead, convert to a floating
929point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +0000930
931.. index:: single: addition
932
Georg Brandl96593ed2007-09-07 14:15:41 +0000933The ``+`` (addition) operator yields the sum of its arguments. The arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000934must either both be numbers or both sequences of the same type. In the former
935case, the numbers are converted to a common type and then added together. In
936the latter case, the sequences are concatenated.
937
938.. index:: single: subtraction
939
940The ``-`` (subtraction) operator yields the difference of its arguments. The
941numeric arguments are first converted to a common type.
942
943
944.. _shifting:
945
946Shifting operations
947===================
948
949.. index:: pair: shifting; operation
950
951The shifting operations have lower priority than the arithmetic operations:
952
953.. productionlist::
954 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
955
Georg Brandl96593ed2007-09-07 14:15:41 +0000956These operators accept integers as arguments. They shift the first argument to
957the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000958
959.. index:: exception: ValueError
960
961A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift
Georg Brandl96593ed2007-09-07 14:15:41 +0000962by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000963
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000964.. note::
965
966 In the current implementation, the right-hand operand is required
Mark Dickinson505add32010-04-06 18:22:06 +0000967 to be at most :attr:`sys.maxsize`. If the right-hand operand is larger than
968 :attr:`sys.maxsize` an :exc:`OverflowError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000969
970.. _bitwise:
971
Christian Heimesfaf2f632008-01-06 16:59:19 +0000972Binary bitwise operations
973=========================
Georg Brandl116aa622007-08-15 14:28:22 +0000974
Christian Heimesfaf2f632008-01-06 16:59:19 +0000975.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000976
977Each of the three bitwise operations has a different priority level:
978
979.. productionlist::
980 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
981 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
982 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
983
Christian Heimesfaf2f632008-01-06 16:59:19 +0000984.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +0000985
Georg Brandl96593ed2007-09-07 14:15:41 +0000986The ``&`` operator yields the bitwise AND of its arguments, which must be
987integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000988
989.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000990 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +0000991 pair: exclusive; or
992
993The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +0000994must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000995
996.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000997 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +0000998 pair: inclusive; or
999
1000The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001001must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001002
1003
1004.. _comparisons:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001005.. _is:
Georg Brandl375aec22011-01-15 17:03:02 +00001006.. _is not:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001007.. _in:
Georg Brandl375aec22011-01-15 17:03:02 +00001008.. _not in:
Georg Brandl116aa622007-08-15 14:28:22 +00001009
1010Comparisons
1011===========
1012
1013.. index:: single: comparison
1014
1015.. index:: pair: C; language
1016
1017Unlike C, all comparison operations in Python have the same priority, which is
1018lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1019C, expressions like ``a < b < c`` have the interpretation that is conventional
1020in mathematics:
1021
1022.. productionlist::
1023 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1024 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1025 : | "is" ["not"] | ["not"] "in"
1026
1027Comparisons yield boolean values: ``True`` or ``False``.
1028
1029.. index:: pair: chaining; comparisons
1030
1031Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1032``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1033cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1034
Guido van Rossum04110fb2007-08-24 16:32:05 +00001035Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1036*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1037to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1038evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001039
Guido van Rossum04110fb2007-08-24 16:32:05 +00001040Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001041*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1042pretty).
1043
1044The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1045values of two objects. The objects need not have the same type. If both are
Georg Brandl9609cea2008-09-09 19:31:57 +00001046numbers, they are converted to a common type. Otherwise, the ``==`` and ``!=``
1047operators *always* consider objects of different types to be unequal, while the
1048``<``, ``>``, ``>=`` and ``<=`` operators raise a :exc:`TypeError` when
1049comparing objects of different types that do not implement these operators for
1050the given pair of types. You can control comparison behavior of objects of
Georg Brandl22b34312009-07-26 14:54:51 +00001051non-built-in types by defining rich comparison methods like :meth:`__gt__`,
Georg Brandl9609cea2008-09-09 19:31:57 +00001052described in section :ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001053
1054Comparison of objects of the same type depends on the type:
1055
1056* Numbers are compared arithmetically.
1057
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001058* The values :const:`float('NaN')` and :const:`Decimal('NaN')` are special.
1059 The are identical to themselves, ``x is x`` but are not equal to themselves,
1060 ``x != x``. Additionally, comparing any value to a not-a-number value
1061 will return ``False``. For example, both ``3 < float('NaN')`` and
1062 ``float('NaN') < 3`` will return ``False``.
1063
Georg Brandl96593ed2007-09-07 14:15:41 +00001064* Bytes objects are compared lexicographically using the numeric values of their
1065 elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001066
Georg Brandl116aa622007-08-15 14:28:22 +00001067* Strings are compared lexicographically using the numeric equivalents (the
Georg Brandl96593ed2007-09-07 14:15:41 +00001068 result of the built-in function :func:`ord`) of their characters. [#]_ String
1069 and bytes object can't be compared!
Georg Brandl116aa622007-08-15 14:28:22 +00001070
1071* Tuples and lists are compared lexicographically using comparison of
1072 corresponding elements. This means that to compare equal, each element must
1073 compare equal and the two sequences must be of the same type and have the same
1074 length.
1075
1076 If not equal, the sequences are ordered the same as their first differing
Mark Dickinsonc48d8342009-02-01 14:18:10 +00001077 elements. For example, ``[1,2,x] <= [1,2,y]`` has the same value as
1078 ``x <= y``. If the corresponding element does not exist, the shorter
Georg Brandl96593ed2007-09-07 14:15:41 +00001079 sequence is ordered first (for example, ``[1,2] < [1,2,3]``).
Georg Brandl116aa622007-08-15 14:28:22 +00001080
Senthil Kumaran07367672010-07-14 20:30:02 +00001081* Mappings (dictionaries) compare equal if and only if they have the same
1082 ``(key, value)`` pairs. Order comparisons ``('<', '<=', '>=', '>')``
1083 raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001084
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001085* Sets and frozensets define comparison operators to mean subset and superset
1086 tests. Those relations do not define total orderings (the two sets ``{1,2}``
1087 and {2,3} are not equal, nor subsets of one another, nor supersets of one
1088 another). Accordingly, sets are not appropriate arguments for functions
1089 which depend on total ordering. For example, :func:`min`, :func:`max`, and
1090 :func:`sorted` produce undefined results given a list of sets as inputs.
1091
Georg Brandl22b34312009-07-26 14:54:51 +00001092* Most other objects of built-in types compare unequal unless they are the same
Georg Brandl116aa622007-08-15 14:28:22 +00001093 object; the choice whether one object is considered smaller or larger than
1094 another one is made arbitrarily but consistently within one execution of a
1095 program.
1096
Georg Brandl7ea9a422012-10-06 13:48:39 +02001097Comparison of objects of the differing types depends on whether either of the
1098types provide explicit support for the comparison. Most numeric types can be
1099compared with one another. When cross-type comparison is not supported, the
1100comparison method returns ``NotImplemented``.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001101
Georg Brandl495f7b52009-10-27 15:28:25 +00001102.. _membership-test-details:
1103
Georg Brandl96593ed2007-09-07 14:15:41 +00001104The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
1105s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not
1106in s`` returns the negation of ``x in s``. All built-in sequences and set types
1107support this as well as dictionary, for which :keyword:`in` tests whether a the
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001108dictionary has a given key. For container types such as list, tuple, set,
Raymond Hettinger0cc818f2008-11-21 10:40:51 +00001109frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001110to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001111
Georg Brandl4b491312007-08-31 09:22:56 +00001112For the string and bytes types, ``x in y`` is true if and only if *x* is a
1113substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1114always considered to be a substring of any other string, so ``"" in "abc"`` will
1115return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001116
Georg Brandl116aa622007-08-15 14:28:22 +00001117For user-defined classes which define the :meth:`__contains__` method, ``x in
1118y`` is true if and only if ``y.__contains__(x)`` is true.
1119
Georg Brandl495f7b52009-10-27 15:28:25 +00001120For user-defined classes which do not define :meth:`__contains__` but do define
1121:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1122produced while iterating over ``y``. If an exception is raised during the
1123iteration, it is as if :keyword:`in` raised that exception.
1124
1125Lastly, the old-style iteration protocol is tried: if a class defines
Georg Brandl116aa622007-08-15 14:28:22 +00001126:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1127integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001128raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001129if :keyword:`in` raised that exception).
1130
1131.. index::
1132 operator: in
1133 operator: not in
1134 pair: membership; test
1135 object: sequence
1136
1137The operator :keyword:`not in` is defined to have the inverse true value of
1138:keyword:`in`.
1139
1140.. index::
1141 operator: is
1142 operator: is not
1143 pair: identity; test
1144
1145The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1146is 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 +00001147yields the inverse truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001148
1149
1150.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001151.. _and:
1152.. _or:
1153.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001154
1155Boolean operations
1156==================
1157
1158.. index::
1159 pair: Conditional; expression
1160 pair: Boolean; operation
1161
Georg Brandl116aa622007-08-15 14:28:22 +00001162.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001163 or_test: `and_test` | `or_test` "or" `and_test`
1164 and_test: `not_test` | `and_test` "and" `not_test`
1165 not_test: `comparison` | "not" `not_test`
1166
1167In the context of Boolean operations, and also when expressions are used by
1168control flow statements, the following values are interpreted as false:
1169``False``, ``None``, numeric zero of all types, and empty strings and containers
1170(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001171other values are interpreted as true. User-defined objects can customize their
1172truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001173
1174.. index:: operator: not
1175
1176The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1177otherwise.
1178
Georg Brandl116aa622007-08-15 14:28:22 +00001179.. index:: operator: and
1180
1181The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1182returned; otherwise, *y* is evaluated and the resulting value is returned.
1183
1184.. index:: operator: or
1185
1186The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1187returned; otherwise, *y* is evaluated and the resulting value is returned.
1188
1189(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1190they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001191argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001192replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1193the desired value. Because :keyword:`not` has to invent a value anyway, it does
1194not bother to return a value of the same type as its argument, so e.g., ``not
1195'foo'`` yields ``False``, not ``''``.)
1196
1197
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001198Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001199=======================
1200
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001201.. index::
1202 pair: conditional; expression
1203 pair: ternary; operator
1204
1205.. productionlist::
1206 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1207 expression: `conditional_expression` | `lambda_form`
1208 expression_nocond: `or_test` | `lambda_form_nocond`
1209
1210Conditional expressions (sometimes called a "ternary operator") have the lowest
1211priority of all Python operations.
1212
1213The expression ``x if C else y`` first evaluates the condition, *C* (*not* *x*);
1214if *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
1215evaluated and its value is returned.
1216
1217See :pep:`308` for more details about conditional expressions.
1218
1219
Georg Brandl116aa622007-08-15 14:28:22 +00001220.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001221.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001222
1223Lambdas
1224=======
1225
1226.. index::
1227 pair: lambda; expression
1228 pair: lambda; form
1229 pair: anonymous; function
1230
1231.. productionlist::
1232 lambda_form: "lambda" [`parameter_list`]: `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +00001233 lambda_form_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001234
1235Lambda forms (lambda expressions) have the same syntactic position as
1236expressions. They are a shorthand to create anonymous functions; the expression
1237``lambda arguments: expression`` yields a function object. The unnamed object
1238behaves like a function object defined with ::
1239
Georg Brandl96593ed2007-09-07 14:15:41 +00001240 def <lambda>(arguments):
Georg Brandl116aa622007-08-15 14:28:22 +00001241 return expression
1242
1243See section :ref:`function` for the syntax of parameter lists. Note that
1244functions created with lambda forms cannot contain statements or annotations.
1245
Georg Brandl116aa622007-08-15 14:28:22 +00001246
1247.. _exprlists:
1248
1249Expression lists
1250================
1251
1252.. index:: pair: expression; list
1253
1254.. productionlist::
1255 expression_list: `expression` ( "," `expression` )* [","]
1256
1257.. index:: object: tuple
1258
1259An expression list containing at least one comma yields a tuple. The length of
1260the tuple is the number of expressions in the list. The expressions are
1261evaluated from left to right.
1262
1263.. index:: pair: trailing; comma
1264
1265The trailing comma is required only to create a single tuple (a.k.a. a
1266*singleton*); it is optional in all other cases. A single expression without a
1267trailing comma doesn't create a tuple, but rather yields the value of that
1268expression. (To create an empty tuple, use an empty pair of parentheses:
1269``()``.)
1270
1271
1272.. _evalorder:
1273
1274Evaluation order
1275================
1276
1277.. index:: pair: evaluation; order
1278
Georg Brandl96593ed2007-09-07 14:15:41 +00001279Python evaluates expressions from left to right. Notice that while evaluating
1280an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001281
1282In the following lines, expressions will be evaluated in the arithmetic order of
1283their suffixes::
1284
1285 expr1, expr2, expr3, expr4
1286 (expr1, expr2, expr3, expr4)
1287 {expr1: expr2, expr3: expr4}
1288 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001289 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001290 expr3, expr4 = expr1, expr2
1291
1292
1293.. _operator-summary:
1294
1295Summary
1296=======
1297
1298.. index:: pair: operator; precedence
1299
1300The following table summarizes the operator precedences in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001301precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001302the same box have the same precedence. Unless the syntax is explicitly given,
1303operators are binary. Operators in the same box group left to right (except for
1304comparisons, including tests, which all have the same precedence and chain from
1305left to right --- see section :ref:`comparisons` --- and exponentiation, which
1306groups from right to left).
1307
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001308
1309+-----------------------------------------------+-------------------------------------+
1310| Operator | Description |
1311+===============================================+=====================================+
1312| :keyword:`lambda` | Lambda expression |
1313+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001314| :keyword:`if` -- :keyword:`else` | Conditional expression |
1315+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001316| :keyword:`or` | Boolean OR |
1317+-----------------------------------------------+-------------------------------------+
1318| :keyword:`and` | Boolean AND |
1319+-----------------------------------------------+-------------------------------------+
1320| :keyword:`not` *x* | Boolean NOT |
1321+-----------------------------------------------+-------------------------------------+
1322| :keyword:`in`, :keyword:`not` :keyword:`in`, | Comparisons, including membership |
1323| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests, |
Georg Brandla5ebc262009-06-03 07:26:22 +00001324| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001325+-----------------------------------------------+-------------------------------------+
1326| ``|`` | Bitwise OR |
1327+-----------------------------------------------+-------------------------------------+
1328| ``^`` | Bitwise XOR |
1329+-----------------------------------------------+-------------------------------------+
1330| ``&`` | Bitwise AND |
1331+-----------------------------------------------+-------------------------------------+
1332| ``<<``, ``>>`` | Shifts |
1333+-----------------------------------------------+-------------------------------------+
1334| ``+``, ``-`` | Addition and subtraction |
1335+-----------------------------------------------+-------------------------------------+
1336| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandlf1d633c2010-09-20 06:29:01 +00001337| | [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001338+-----------------------------------------------+-------------------------------------+
1339| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1340+-----------------------------------------------+-------------------------------------+
1341| ``**`` | Exponentiation [#]_ |
1342+-----------------------------------------------+-------------------------------------+
1343| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1344| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1345+-----------------------------------------------+-------------------------------------+
1346| ``(expressions...)``, | Binding or tuple display, |
1347| ``[expressions...]``, | list display, |
1348| ``{key:datum...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001349| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001350+-----------------------------------------------+-------------------------------------+
1351
Georg Brandl116aa622007-08-15 14:28:22 +00001352
1353.. rubric:: Footnotes
1354
Georg Brandl116aa622007-08-15 14:28:22 +00001355.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1356 true numerically due to roundoff. For example, and assuming a platform on which
1357 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1358 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001359 1e100``, which is numerically exactly equal to ``1e100``. The function
1360 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001361 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1362 is more appropriate depends on the application.
1363
1364.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001365 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001366 cases, Python returns the latter result, in order to preserve that
1367 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1368
Georg Brandl96593ed2007-09-07 14:15:41 +00001369.. [#] While comparisons between strings make sense at the byte level, they may
1370 be counter-intuitive to users. For example, the strings ``"\u00C7"`` and
1371 ``"\u0327\u0043"`` compare differently, even though they both represent the
Georg Brandlae2dbe22009-03-13 19:04:40 +00001372 same unicode character (LATIN CAPITAL LETTER C WITH CEDILLA). To compare
Georg Brandl9afde1c2007-11-01 20:32:30 +00001373 strings in a human recognizable way, compare using
1374 :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001375
Georg Brandl48310cd2009-01-03 21:18:54 +00001376.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001377 descriptors, you may notice seemingly unusual behaviour in certain uses of
1378 the :keyword:`is` operator, like those involving comparisons between instance
1379 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001380
Georg Brandl063f2372010-12-01 15:32:43 +00001381.. [#] The ``%`` operator is also used for string formatting; the same
1382 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001383
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001384.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1385 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.