blob: c0132bd4717c99d135d79b4e4a2db08c53522589 [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
Georg Brandldec3b3f2013-04-14 10:13:42 +020087them. The transformation inserts the class name, with leading underscores
88removed and a single underscore inserted, in front of the name. For example,
89the identifier ``__spam`` occurring in a class named ``Ham`` will be transformed
90to ``_Ham__spam``. This transformation is independent of the syntactical
91context in which the identifier is used. If the transformed name is extremely
92long (longer than 255 characters), implementation defined truncation may happen.
93If the class name consists only of underscores, no transformation is done.
Georg Brandl116aa622007-08-15 14:28:22 +000094
Georg Brandl116aa622007-08-15 14:28:22 +000095
96.. _atom-literals:
97
98Literals
99--------
100
101.. index:: single: literal
102
Georg Brandl96593ed2007-09-07 14:15:41 +0000103Python supports string and bytes literals and various numeric literals:
Georg Brandl116aa622007-08-15 14:28:22 +0000104
105.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000106 literal: `stringliteral` | `bytesliteral`
107 : | `integer` | `floatnumber` | `imagnumber`
Georg Brandl116aa622007-08-15 14:28:22 +0000108
Georg Brandl96593ed2007-09-07 14:15:41 +0000109Evaluation of a literal yields an object of the given type (string, bytes,
110integer, floating point number, complex number) with the given value. The value
111may be approximated in the case of floating point and imaginary (complex)
Georg Brandl116aa622007-08-15 14:28:22 +0000112literals. See section :ref:`literals` for details.
113
114.. index::
115 triple: immutable; data; type
116 pair: immutable; object
117
Terry Jan Reedyead1de22012-02-17 19:56:58 -0500118All literals correspond to immutable data types, and hence the object's identity
119is less important than its value. Multiple evaluations of literals with the
120same value (either the same occurrence in the program text or a different
121occurrence) may obtain the same object or a different object with the same
122value.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124
125.. _parenthesized:
126
127Parenthesized forms
128-------------------
129
130.. index:: single: parenthesized form
131
132A parenthesized form is an optional expression list enclosed in parentheses:
133
134.. productionlist::
135 parenth_form: "(" [`expression_list`] ")"
136
137A parenthesized expression list yields whatever that expression list yields: if
138the list contains at least one comma, it yields a tuple; otherwise, it yields
139the single expression that makes up the expression list.
140
141.. index:: pair: empty; tuple
142
143An empty pair of parentheses yields an empty tuple object. Since tuples are
144immutable, the rules for literals apply (i.e., two occurrences of the empty
145tuple may or may not yield the same object).
146
147.. index::
148 single: comma
149 pair: tuple; display
150
151Note that tuples are not formed by the parentheses, but rather by use of the
152comma operator. The exception is the empty tuple, for which parentheses *are*
153required --- allowing unparenthesized "nothing" in expressions would cause
154ambiguities and allow common typos to pass uncaught.
155
156
Georg Brandl96593ed2007-09-07 14:15:41 +0000157.. _comprehensions:
158
159Displays for lists, sets and dictionaries
160-----------------------------------------
161
162For constructing a list, a set or a dictionary Python provides special syntax
163called "displays", each of them in two flavors:
164
165* either the container contents are listed explicitly, or
166
167* they are computed via a set of looping and filtering instructions, called a
168 :dfn:`comprehension`.
169
170Common syntax elements for comprehensions are:
171
172.. productionlist::
173 comprehension: `expression` `comp_for`
174 comp_for: "for" `target_list` "in" `or_test` [`comp_iter`]
175 comp_iter: `comp_for` | `comp_if`
176 comp_if: "if" `expression_nocond` [`comp_iter`]
177
178The comprehension consists of a single expression followed by at least one
179:keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` clauses.
180In this case, the elements of the new container are those that would be produced
181by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
182nesting from left to right, and evaluating the expression to produce an element
183each time the innermost block is reached.
184
Georg Brandl02c30562007-09-07 17:52:53 +0000185Note that the comprehension is executed in a separate scope, so names assigned
186to in the target list don't "leak" in the enclosing scope.
187
Georg Brandl96593ed2007-09-07 14:15:41 +0000188
Georg Brandl116aa622007-08-15 14:28:22 +0000189.. _lists:
190
191List displays
192-------------
193
194.. index::
195 pair: list; display
196 pair: list; comprehensions
Georg Brandl96593ed2007-09-07 14:15:41 +0000197 pair: empty; list
198 object: list
Georg Brandl116aa622007-08-15 14:28:22 +0000199
200A list display is a possibly empty series of expressions enclosed in square
201brackets:
202
203.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000204 list_display: "[" [`expression_list` | `comprehension`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Georg Brandl96593ed2007-09-07 14:15:41 +0000206A list display yields a new list object, the contents being specified by either
207a list of expressions or a comprehension. When a comma-separated list of
208expressions is supplied, its elements are evaluated from left to right and
209placed into the list object in that order. When a comprehension is supplied,
210the list is constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000211
212
Georg Brandl96593ed2007-09-07 14:15:41 +0000213.. _set:
Georg Brandl116aa622007-08-15 14:28:22 +0000214
Georg Brandl96593ed2007-09-07 14:15:41 +0000215Set displays
216------------
Georg Brandl116aa622007-08-15 14:28:22 +0000217
Georg Brandl96593ed2007-09-07 14:15:41 +0000218.. index:: pair: set; display
219 object: set
Georg Brandl116aa622007-08-15 14:28:22 +0000220
Georg Brandl96593ed2007-09-07 14:15:41 +0000221A set display is denoted by curly braces and distinguishable from dictionary
222displays by the lack of colons separating keys and values:
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224.. productionlist::
Georg Brandl528cdb12008-09-21 07:09:51 +0000225 set_display: "{" (`expression_list` | `comprehension`) "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000226
Georg Brandl96593ed2007-09-07 14:15:41 +0000227A set display yields a new mutable set object, the contents being specified by
228either a sequence of expressions or a comprehension. When a comma-separated
229list of expressions is supplied, its elements are evaluated from left to right
230and added to the set object. When a comprehension is supplied, the set is
231constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000232
Georg Brandl528cdb12008-09-21 07:09:51 +0000233An empty set cannot be constructed with ``{}``; this literal constructs an empty
234dictionary.
Christian Heimes78644762008-03-04 23:39:23 +0000235
236
Georg Brandl116aa622007-08-15 14:28:22 +0000237.. _dict:
238
239Dictionary displays
240-------------------
241
242.. index:: pair: dictionary; display
Georg Brandl96593ed2007-09-07 14:15:41 +0000243 key, datum, key/datum pair
244 object: dictionary
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246A dictionary display is a possibly empty series of key/datum pairs enclosed in
247curly braces:
248
249.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000250 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000251 key_datum_list: `key_datum` ("," `key_datum`)* [","]
252 key_datum: `expression` ":" `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +0000253 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255A dictionary display yields a new dictionary object.
256
Georg Brandl96593ed2007-09-07 14:15:41 +0000257If a comma-separated sequence of key/datum pairs is given, they are evaluated
258from left to right to define the entries of the dictionary: each key object is
259used as a key into the dictionary to store the corresponding datum. This means
260that you can specify the same key multiple times in the key/datum list, and the
261final dictionary's value for that key will be the last one given.
262
263A dict comprehension, in contrast to list and set comprehensions, needs two
264expressions separated with a colon followed by the usual "for" and "if" clauses.
265When the comprehension is run, the resulting key and value elements are inserted
266in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000269 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000272:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000273all mutable objects.) Clashes between duplicate keys are not detected; the last
274datum (textually rightmost in the display) stored for a given key value
275prevails.
276
277
Georg Brandl96593ed2007-09-07 14:15:41 +0000278.. _genexpr:
279
280Generator expressions
281---------------------
282
283.. index:: pair: generator; expression
284 object: generator
285
286A generator expression is a compact generator notation in parentheses:
287
288.. productionlist::
289 generator_expression: "(" `expression` `comp_for` ")"
290
291A generator expression yields a new generator object. Its syntax is the same as
292for comprehensions, except that it is enclosed in parentheses instead of
293brackets or curly braces.
294
295Variables used in the generator expression are evaluated lazily when the
Ezio Melotti7fa82222012-10-12 13:42:08 +0300296:meth:`~generator.__next__` method is called for generator object (in the same
297fashion as normal generators). However, the leftmost :keyword:`for` clause is
298immediately evaluated, so that an error produced by it can be seen before any
299other possible error in the code that handles the generator expression.
300Subsequent :keyword:`for` clauses cannot be evaluated immediately since they
301may depend on the previous :keyword:`for` loop. For example: ``(x*y for x in
302range(10) for y in bar(x))``.
Georg Brandl96593ed2007-09-07 14:15:41 +0000303
304The parentheses can be omitted on calls with only one argument. See section
305:ref:`calls` for the detail.
306
307
Georg Brandl116aa622007-08-15 14:28:22 +0000308.. _yieldexpr:
309
310Yield expressions
311-----------------
312
313.. index::
314 keyword: yield
315 pair: yield; expression
316 pair: generator; function
317
318.. productionlist::
319 yield_atom: "(" `yield_expression` ")"
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000320 yield_expression: "yield" [`expression_list` | "from" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000321
Chris Jerdonek2654b862012-12-23 15:31:57 -0800322The :keyword:`yield` expression is only used when defining a :term:`generator`
323function,
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
Ezio Melotti7fa82222012-10-12 13:42:08 +0300397 with a :meth:`~generator.__next__` method, the current :keyword:`yield`
398 expression always evaluates to :const:`None`. The execution then continues
399 to the next :keyword:`yield` expression, where the generator is suspended
400 again, and the value of the :token:`expression_list` is returned to
401 :meth:`next`'s caller.
Georg Brandl96593ed2007-09-07 14:15:41 +0000402 If the generator exits without yielding another value, a :exc:`StopIteration`
403 exception is raised.
404
405 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
406 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000407
408
409.. method:: generator.send(value)
410
411 Resumes the execution and "sends" a value into the generator function. The
412 ``value`` argument becomes the result of the current :keyword:`yield`
413 expression. The :meth:`send` method returns the next value yielded by the
414 generator, or raises :exc:`StopIteration` if the generator exits without
Georg Brandl96593ed2007-09-07 14:15:41 +0000415 yielding another value. When :meth:`send` is called to start the generator,
416 it must be called with :const:`None` as the argument, because there is no
Christian Heimesc3f30c42008-02-22 16:37:40 +0000417 :keyword:`yield` expression that could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000418
419
420.. method:: generator.throw(type[, value[, traceback]])
421
422 Raises an exception of type ``type`` at the point where generator was paused,
423 and returns the next value yielded by the generator function. If the generator
424 exits without yielding another value, a :exc:`StopIteration` exception is
425 raised. If the generator function does not catch the passed-in exception, or
426 raises a different exception, then that exception propagates to the caller.
427
428.. index:: exception: GeneratorExit
429
430
431.. method:: generator.close()
432
433 Raises a :exc:`GeneratorExit` at the point where the generator function was
Georg Brandl96593ed2007-09-07 14:15:41 +0000434 paused. If the generator function then raises :exc:`StopIteration` (by
435 exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by
436 not catching the exception), close returns to its caller. If the generator
437 yields a value, a :exc:`RuntimeError` is raised. If the generator raises any
438 other exception, it is propagated to the caller. :meth:`close` does nothing
439 if the generator has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000440
Chris Jerdonek2654b862012-12-23 15:31:57 -0800441
442.. index:: single: yield; examples
443
444Examples
445^^^^^^^^
446
Georg Brandl116aa622007-08-15 14:28:22 +0000447Here is a simple example that demonstrates the behavior of generators and
448generator functions::
449
450 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000451 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000452 ... try:
453 ... while True:
454 ... try:
455 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000456 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000457 ... value = e
458 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000459 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000460 ...
461 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000462 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000463 Execution starts when 'next()' is called for the first time.
464 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000465 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000466 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000467 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000468 2
469 >>> generator.throw(TypeError, "spam")
470 TypeError('spam',)
471 >>> generator.close()
472 Don't forget to clean up when 'close()' is called.
473
Chris Jerdonek2654b862012-12-23 15:31:57 -0800474For examples using ``yield from``, see :ref:`pep-380` in "What's New in
475Python."
476
Georg Brandl116aa622007-08-15 14:28:22 +0000477
478.. seealso::
479
Georg Brandl02c30562007-09-07 17:52:53 +0000480 :pep:`0255` - Simple Generators
481 The proposal for adding generators and the :keyword:`yield` statement to Python.
482
Georg Brandl116aa622007-08-15 14:28:22 +0000483 :pep:`0342` - Coroutines via Enhanced Generators
Georg Brandl96593ed2007-09-07 14:15:41 +0000484 The proposal to enhance the API and syntax of generators, making them
485 usable as simple coroutines.
Georg Brandl116aa622007-08-15 14:28:22 +0000486
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000487 :pep:`0380` - Syntax for Delegating to a Subgenerator
488 The proposal to introduce the :token:`yield_from` syntax, making delegation
489 to sub-generators easy.
490
Georg Brandl116aa622007-08-15 14:28:22 +0000491
492.. _primaries:
493
494Primaries
495=========
496
497.. index:: single: primary
498
499Primaries represent the most tightly bound operations of the language. Their
500syntax is:
501
502.. productionlist::
503 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
504
505
506.. _attribute-references:
507
508Attribute references
509--------------------
510
511.. index:: pair: attribute; reference
512
513An attribute reference is a primary followed by a period and a name:
514
515.. productionlist::
516 attributeref: `primary` "." `identifier`
517
518.. index::
519 exception: AttributeError
520 object: module
521 object: list
522
523The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000524references, which most objects do. This object is then asked to produce the
525attribute whose name is the identifier (which can be customized by overriding
526the :meth:`__getattr__` method). If this attribute is not available, the
527exception :exc:`AttributeError` is raised. Otherwise, the type and value of the
528object produced is determined by the object. Multiple evaluations of the same
529attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000530
531
532.. _subscriptions:
533
534Subscriptions
535-------------
536
537.. index:: single: subscription
538
539.. index::
540 object: sequence
541 object: mapping
542 object: string
543 object: tuple
544 object: list
545 object: dictionary
546 pair: sequence; item
547
548A subscription selects an item of a sequence (string, tuple or list) or mapping
549(dictionary) object:
550
551.. productionlist::
552 subscription: `primary` "[" `expression_list` "]"
553
Georg Brandl96593ed2007-09-07 14:15:41 +0000554The primary must evaluate to an object that supports subscription, e.g. a list
555or dictionary. User-defined objects can support subscription by defining a
556:meth:`__getitem__` method.
557
558For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000559
560If the primary is a mapping, the expression list must evaluate to an object
561whose value is one of the keys of the mapping, and the subscription selects the
562value in the mapping that corresponds to that key. (The expression list is a
563tuple except if it has exactly one item.)
564
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000565If the primary is a sequence, the expression (list) must evaluate to an integer
566or a slice (as discussed in the following section).
567
568The formal syntax makes no special provision for negative indices in
569sequences; however, built-in sequences all provide a :meth:`__getitem__`
570method that interprets negative indices by adding the length of the sequence
571to the index (so that ``x[-1]`` selects the last item of ``x``). The
572resulting value must be a nonnegative integer less than the number of items in
573the sequence, and the subscription selects the item whose index is that value
574(counting from zero). Since the support for negative indices and slicing
575occurs in the object's :meth:`__getitem__` method, subclasses overriding
576this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000577
578.. index::
579 single: character
580 pair: string; item
581
582A string's items are characters. A character is not a separate data type but a
583string of exactly one character.
584
585
586.. _slicings:
587
588Slicings
589--------
590
591.. index::
592 single: slicing
593 single: slice
594
595.. index::
596 object: sequence
597 object: string
598 object: tuple
599 object: list
600
601A slicing selects a range of items in a sequence object (e.g., a string, tuple
602or list). Slicings may be used as expressions or as targets in assignment or
603:keyword:`del` statements. The syntax for a slicing:
604
605.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000606 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000607 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000608 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000609 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000610 lower_bound: `expression`
611 upper_bound: `expression`
612 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000613
614There is ambiguity in the formal syntax here: anything that looks like an
615expression list also looks like a slice list, so any subscription can be
616interpreted as a slicing. Rather than further complicating the syntax, this is
617disambiguated by defining that in this case the interpretation as a subscription
618takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000619slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000620
621.. index::
622 single: start (slice object attribute)
623 single: stop (slice object attribute)
624 single: step (slice object attribute)
625
Thomas Wouters53de1902007-09-04 09:03:59 +0000626The semantics for a slicing are as follows. The primary must evaluate to a
Georg Brandl96593ed2007-09-07 14:15:41 +0000627mapping object, and it is indexed (using the same :meth:`__getitem__` method as
628normal subscription) with a key that is constructed from the slice list, as
629follows. If the slice list contains at least one comma, the key is a tuple
630containing the conversion of the slice items; otherwise, the conversion of the
631lone slice item is the key. The conversion of a slice item that is an
632expression is that expression. The conversion of a proper slice is a slice
633object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
634:attr:`step` attributes are the values of the expressions given as lower bound,
635upper bound and stride, respectively, substituting ``None`` for missing
636expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000637
638
Chris Jerdonekb4309942012-12-25 14:54:44 -0800639.. index::
640 object: callable
641 single: call
642 single: argument; call semantics
643
Georg Brandl116aa622007-08-15 14:28:22 +0000644.. _calls:
645
646Calls
647-----
648
Chris Jerdonekb4309942012-12-25 14:54:44 -0800649A call calls a callable object (e.g., a :term:`function`) with a possibly empty
650series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000651
652.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000653 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000654 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000655 : ["," "*" `expression`] ["," `keyword_arguments`]
656 : ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000657 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000658 : ["," `keyword_arguments`] ["," "**" `expression`]
659 : | "*" `expression` ["," `keyword_arguments`] ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000660 : | "**" `expression`
661 positional_arguments: `expression` ("," `expression`)*
662 keyword_arguments: `keyword_item` ("," `keyword_item`)*
663 keyword_item: `identifier` "=" `expression`
664
665A trailing comma may be present after the positional and keyword arguments but
666does not affect the semantics.
667
Chris Jerdonekb4309942012-12-25 14:54:44 -0800668.. index::
669 single: parameter; call semantics
670
Georg Brandl116aa622007-08-15 14:28:22 +0000671The primary must evaluate to a callable object (user-defined functions, built-in
672functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000673instances, and all objects having a :meth:`__call__` method are callable). All
674argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800675to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000676
677.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000678
679If keyword arguments are present, they are first converted to positional
680arguments, as follows. First, a list of unfilled slots is created for the
681formal parameters. If there are N positional arguments, they are placed in the
682first N slots. Next, for each keyword argument, the identifier is used to
683determine the corresponding slot (if the identifier is the same as the first
684formal parameter name, the first slot is used, and so on). If the slot is
685already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
686the argument is placed in the slot, filling it (even if the expression is
687``None``, it fills the slot). When all arguments have been processed, the slots
688that are still unfilled are filled with the corresponding default value from the
689function definition. (Default values are calculated, once, when the function is
690defined; thus, a mutable object such as a list or dictionary used as default
691value will be shared by all calls that don't specify an argument value for the
692corresponding slot; this should usually be avoided.) If there are any unfilled
693slots for which no default value is specified, a :exc:`TypeError` exception is
694raised. Otherwise, the list of filled slots is used as the argument list for
695the call.
696
Georg Brandl495f7b52009-10-27 15:28:25 +0000697.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000698
Georg Brandl495f7b52009-10-27 15:28:25 +0000699 An implementation may provide built-in functions whose positional parameters
700 do not have names, even if they are 'named' for the purpose of documentation,
701 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000702 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000703 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000704
Georg Brandl116aa622007-08-15 14:28:22 +0000705If there are more positional arguments than there are formal parameter slots, a
706:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
707``*identifier`` is present; in this case, that formal parameter receives a tuple
708containing the excess positional arguments (or an empty tuple if there were no
709excess positional arguments).
710
711If any keyword argument does not correspond to a formal parameter name, a
712:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
713``**identifier`` is present; in this case, that formal parameter receives a
714dictionary containing the excess keyword arguments (using the keywords as keys
715and the argument values as corresponding values), or a (new) empty dictionary if
716there were no excess keyword arguments.
717
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300718.. index::
719 single: *; in function calls
720
Georg Brandl116aa622007-08-15 14:28:22 +0000721If the syntax ``*expression`` appears in the function call, ``expression`` must
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300722evaluate to an iterable. Elements from this iterable are treated as if they
723were additional positional arguments; if there are positional arguments
Ezio Melotti59256322011-07-30 21:25:22 +0300724*x1*, ..., *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*,
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300725this is equivalent to a call with M+N positional arguments *x1*, ..., *xN*,
726*y1*, ..., *yM*.
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000728A consequence of this is that although the ``*expression`` syntax may appear
729*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000730(and the ``**expression`` argument, if any -- see below). So::
731
732 >>> def f(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000733 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000734 ...
735 >>> f(b=1, *(2,))
736 2 1
737 >>> f(a=1, *(2,))
738 Traceback (most recent call last):
739 File "<stdin>", line 1, in ?
740 TypeError: f() got multiple values for keyword argument 'a'
741 >>> f(1, *(2,))
742 1 2
743
744It is unusual for both keyword arguments and the ``*expression`` syntax to be
745used in the same call, so in practice this confusion does not arise.
746
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300747.. index::
748 single: **; in function calls
749
Georg Brandl116aa622007-08-15 14:28:22 +0000750If the syntax ``**expression`` appears in the function call, ``expression`` must
751evaluate to a mapping, the contents of which are treated as additional keyword
752arguments. In the case of a keyword appearing in both ``expression`` and as an
753explicit keyword argument, a :exc:`TypeError` exception is raised.
754
755Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
756used as positional argument slots or as keyword argument names.
757
758A call always returns some value, possibly ``None``, unless it raises an
759exception. How this value is computed depends on the type of the callable
760object.
761
762If it is---
763
764a user-defined function:
765 .. index::
766 pair: function; call
767 triple: user-defined; function; call
768 object: user-defined function
769 object: function
770
771 The code block for the function is executed, passing it the argument list. The
772 first thing the code block will do is bind the formal parameters to the
773 arguments; this is described in section :ref:`function`. When the code block
774 executes a :keyword:`return` statement, this specifies the return value of the
775 function call.
776
777a built-in function or method:
778 .. index::
779 pair: function; call
780 pair: built-in function; call
781 pair: method; call
782 pair: built-in method; call
783 object: built-in method
784 object: built-in function
785 object: method
786 object: function
787
788 The result is up to the interpreter; see :ref:`built-in-funcs` for the
789 descriptions of built-in functions and methods.
790
791a class object:
792 .. index::
793 object: class
794 pair: class object; call
795
796 A new instance of that class is returned.
797
798a class instance method:
799 .. index::
800 object: class instance
801 object: instance
802 pair: class instance; call
803
804 The corresponding user-defined function is called, with an argument list that is
805 one longer than the argument list of the call: the instance becomes the first
806 argument.
807
808a class instance:
809 .. index::
810 pair: instance; call
811 single: __call__() (object method)
812
813 The class must define a :meth:`__call__` method; the effect is then the same as
814 if that method was called.
815
816
817.. _power:
818
819The power operator
820==================
821
822The power operator binds more tightly than unary operators on its left; it binds
823less tightly than unary operators on its right. The syntax is:
824
825.. productionlist::
826 power: `primary` ["**" `u_expr`]
827
828Thus, in an unparenthesized sequence of power and unary operators, the operators
829are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +0000830for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000831
832The power operator has the same semantics as the built-in :func:`pow` function,
833when called with two arguments: it yields its left argument raised to the power
834of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +0000835type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +0000836
Georg Brandl96593ed2007-09-07 14:15:41 +0000837For int operands, the result has the same type as the operands unless the second
838argument is negative; in that case, all arguments are converted to float and a
839float result is delivered. For example, ``10**2`` returns ``100``, but
840``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +0000843Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +0000844number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000845
846
847.. _unary:
848
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000849Unary arithmetic and bitwise operations
850=======================================
Georg Brandl116aa622007-08-15 14:28:22 +0000851
852.. index::
853 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +0000854 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000855
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000856All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +0000857
858.. productionlist::
859 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
860
861.. index::
862 single: negation
863 single: minus
864
865The unary ``-`` (minus) operator yields the negation of its numeric argument.
866
867.. index:: single: plus
868
869The unary ``+`` (plus) operator yields its numeric argument unchanged.
870
871.. index:: single: inversion
872
Christian Heimesfaf2f632008-01-06 16:59:19 +0000873
Georg Brandl95817b32008-05-11 14:30:18 +0000874The unary ``~`` (invert) operator yields the bitwise inversion of its integer
875argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
876applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000877
878.. index:: exception: TypeError
879
880In all three cases, if the argument does not have the proper type, a
881:exc:`TypeError` exception is raised.
882
883
884.. _binary:
885
886Binary arithmetic operations
887============================
888
889.. index:: triple: binary; arithmetic; operation
890
891The binary arithmetic operations have the conventional priority levels. Note
892that some of these operations also apply to certain non-numeric types. Apart
893from the power operator, there are only two levels, one for multiplicative
894operators and one for additive operators:
895
896.. productionlist::
897 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
898 : | `m_expr` "%" `u_expr`
899 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
900
901.. index:: single: multiplication
902
903The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +0000904arguments must either both be numbers, or one argument must be an integer and
905the other must be a sequence. In the former case, the numbers are converted to a
906common type and then multiplied together. In the latter case, sequence
907repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000908
909.. index::
910 exception: ZeroDivisionError
911 single: division
912
913The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
914their arguments. The numeric arguments are first converted to a common type.
Georg Brandl96593ed2007-09-07 14:15:41 +0000915Integer division yields a float, while floor division of integers results in an
916integer; the result is that of mathematical division with the 'floor' function
917applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
918exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000919
920.. index:: single: modulo
921
922The ``%`` (modulo) operator yields the remainder from the division of the first
923argument by the second. The numeric arguments are first converted to a common
924type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
925arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
926(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
927result with the same sign as its second operand (or zero); the absolute value of
928the result is strictly smaller than the absolute value of the second operand
929[#]_.
930
Georg Brandl96593ed2007-09-07 14:15:41 +0000931The floor division and modulo operators are connected by the following
932identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
933connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
934x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000935
936In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +0000937also overloaded by string objects to perform old-style string formatting (also
938known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +0000939Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +0000940
941The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +0000942function are not defined for complex numbers. Instead, convert to a floating
943point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +0000944
945.. index:: single: addition
946
Georg Brandl96593ed2007-09-07 14:15:41 +0000947The ``+`` (addition) operator yields the sum of its arguments. The arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000948must either both be numbers or both sequences of the same type. In the former
949case, the numbers are converted to a common type and then added together. In
950the latter case, the sequences are concatenated.
951
952.. index:: single: subtraction
953
954The ``-`` (subtraction) operator yields the difference of its arguments. The
955numeric arguments are first converted to a common type.
956
957
958.. _shifting:
959
960Shifting operations
961===================
962
963.. index:: pair: shifting; operation
964
965The shifting operations have lower priority than the arithmetic operations:
966
967.. productionlist::
968 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
969
Georg Brandl96593ed2007-09-07 14:15:41 +0000970These operators accept integers as arguments. They shift the first argument to
971the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000972
973.. index:: exception: ValueError
974
975A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift
Georg Brandl96593ed2007-09-07 14:15:41 +0000976by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000977
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000978.. note::
979
980 In the current implementation, the right-hand operand is required
Mark Dickinson505add32010-04-06 18:22:06 +0000981 to be at most :attr:`sys.maxsize`. If the right-hand operand is larger than
982 :attr:`sys.maxsize` an :exc:`OverflowError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000983
984.. _bitwise:
985
Christian Heimesfaf2f632008-01-06 16:59:19 +0000986Binary bitwise operations
987=========================
Georg Brandl116aa622007-08-15 14:28:22 +0000988
Christian Heimesfaf2f632008-01-06 16:59:19 +0000989.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000990
991Each of the three bitwise operations has a different priority level:
992
993.. productionlist::
994 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
995 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
996 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
997
Christian Heimesfaf2f632008-01-06 16:59:19 +0000998.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +0000999
Georg Brandl96593ed2007-09-07 14:15:41 +00001000The ``&`` operator yields the bitwise AND of its arguments, which must be
1001integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001002
1003.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001004 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +00001005 pair: exclusive; or
1006
1007The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001008must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001009
1010.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +00001011 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +00001012 pair: inclusive; or
1013
1014The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +00001015must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +00001016
1017
1018.. _comparisons:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001019.. _is:
Georg Brandl375aec22011-01-15 17:03:02 +00001020.. _is not:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001021.. _in:
Georg Brandl375aec22011-01-15 17:03:02 +00001022.. _not in:
Georg Brandl116aa622007-08-15 14:28:22 +00001023
1024Comparisons
1025===========
1026
1027.. index:: single: comparison
1028
1029.. index:: pair: C; language
1030
1031Unlike C, all comparison operations in Python have the same priority, which is
1032lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1033C, expressions like ``a < b < c`` have the interpretation that is conventional
1034in mathematics:
1035
1036.. productionlist::
1037 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1038 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1039 : | "is" ["not"] | ["not"] "in"
1040
1041Comparisons yield boolean values: ``True`` or ``False``.
1042
1043.. index:: pair: chaining; comparisons
1044
1045Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1046``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1047cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1048
Guido van Rossum04110fb2007-08-24 16:32:05 +00001049Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1050*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1051to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1052evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001053
Guido van Rossum04110fb2007-08-24 16:32:05 +00001054Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001055*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1056pretty).
1057
1058The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1059values of two objects. The objects need not have the same type. If both are
Georg Brandl9609cea2008-09-09 19:31:57 +00001060numbers, they are converted to a common type. Otherwise, the ``==`` and ``!=``
1061operators *always* consider objects of different types to be unequal, while the
1062``<``, ``>``, ``>=`` and ``<=`` operators raise a :exc:`TypeError` when
1063comparing objects of different types that do not implement these operators for
1064the given pair of types. You can control comparison behavior of objects of
Georg Brandl22b34312009-07-26 14:54:51 +00001065non-built-in types by defining rich comparison methods like :meth:`__gt__`,
Georg Brandl9609cea2008-09-09 19:31:57 +00001066described in section :ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001067
1068Comparison of objects of the same type depends on the type:
1069
1070* Numbers are compared arithmetically.
1071
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001072* The values :const:`float('NaN')` and :const:`Decimal('NaN')` are special.
1073 The are identical to themselves, ``x is x`` but are not equal to themselves,
1074 ``x != x``. Additionally, comparing any value to a not-a-number value
1075 will return ``False``. For example, both ``3 < float('NaN')`` and
1076 ``float('NaN') < 3`` will return ``False``.
1077
Georg Brandl96593ed2007-09-07 14:15:41 +00001078* Bytes objects are compared lexicographically using the numeric values of their
1079 elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001080
Georg Brandl116aa622007-08-15 14:28:22 +00001081* Strings are compared lexicographically using the numeric equivalents (the
Georg Brandl96593ed2007-09-07 14:15:41 +00001082 result of the built-in function :func:`ord`) of their characters. [#]_ String
1083 and bytes object can't be compared!
Georg Brandl116aa622007-08-15 14:28:22 +00001084
1085* Tuples and lists are compared lexicographically using comparison of
1086 corresponding elements. This means that to compare equal, each element must
1087 compare equal and the two sequences must be of the same type and have the same
1088 length.
1089
1090 If not equal, the sequences are ordered the same as their first differing
Mark Dickinsonc48d8342009-02-01 14:18:10 +00001091 elements. For example, ``[1,2,x] <= [1,2,y]`` has the same value as
1092 ``x <= y``. If the corresponding element does not exist, the shorter
Georg Brandl96593ed2007-09-07 14:15:41 +00001093 sequence is ordered first (for example, ``[1,2] < [1,2,3]``).
Georg Brandl116aa622007-08-15 14:28:22 +00001094
Senthil Kumaran07367672010-07-14 20:30:02 +00001095* Mappings (dictionaries) compare equal if and only if they have the same
1096 ``(key, value)`` pairs. Order comparisons ``('<', '<=', '>=', '>')``
1097 raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001098
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001099* Sets and frozensets define comparison operators to mean subset and superset
1100 tests. Those relations do not define total orderings (the two sets ``{1,2}``
1101 and {2,3} are not equal, nor subsets of one another, nor supersets of one
1102 another). Accordingly, sets are not appropriate arguments for functions
1103 which depend on total ordering. For example, :func:`min`, :func:`max`, and
1104 :func:`sorted` produce undefined results given a list of sets as inputs.
1105
Georg Brandl22b34312009-07-26 14:54:51 +00001106* Most other objects of built-in types compare unequal unless they are the same
Georg Brandl116aa622007-08-15 14:28:22 +00001107 object; the choice whether one object is considered smaller or larger than
1108 another one is made arbitrarily but consistently within one execution of a
1109 program.
1110
Georg Brandl7ea9a422012-10-06 13:48:39 +02001111Comparison of objects of the differing types depends on whether either of the
1112types provide explicit support for the comparison. Most numeric types can be
1113compared with one another. When cross-type comparison is not supported, the
1114comparison method returns ``NotImplemented``.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001115
Georg Brandl495f7b52009-10-27 15:28:25 +00001116.. _membership-test-details:
1117
Georg Brandl96593ed2007-09-07 14:15:41 +00001118The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
1119s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not
1120in s`` returns the negation of ``x in s``. All built-in sequences and set types
1121support this as well as dictionary, for which :keyword:`in` tests whether a the
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001122dictionary has a given key. For container types such as list, tuple, set,
Raymond Hettinger0cc818f2008-11-21 10:40:51 +00001123frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001124to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001125
Georg Brandl4b491312007-08-31 09:22:56 +00001126For the string and bytes types, ``x in y`` is true if and only if *x* is a
1127substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1128always considered to be a substring of any other string, so ``"" in "abc"`` will
1129return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001130
Georg Brandl116aa622007-08-15 14:28:22 +00001131For user-defined classes which define the :meth:`__contains__` method, ``x in
1132y`` is true if and only if ``y.__contains__(x)`` is true.
1133
Georg Brandl495f7b52009-10-27 15:28:25 +00001134For user-defined classes which do not define :meth:`__contains__` but do define
1135:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1136produced while iterating over ``y``. If an exception is raised during the
1137iteration, it is as if :keyword:`in` raised that exception.
1138
1139Lastly, the old-style iteration protocol is tried: if a class defines
Georg Brandl116aa622007-08-15 14:28:22 +00001140:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1141integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001142raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001143if :keyword:`in` raised that exception).
1144
1145.. index::
1146 operator: in
1147 operator: not in
1148 pair: membership; test
1149 object: sequence
1150
1151The operator :keyword:`not in` is defined to have the inverse true value of
1152:keyword:`in`.
1153
1154.. index::
1155 operator: is
1156 operator: is not
1157 pair: identity; test
1158
1159The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1160is 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 +00001161yields the inverse truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001162
1163
1164.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001165.. _and:
1166.. _or:
1167.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001168
1169Boolean operations
1170==================
1171
1172.. index::
1173 pair: Conditional; expression
1174 pair: Boolean; operation
1175
Georg Brandl116aa622007-08-15 14:28:22 +00001176.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001177 or_test: `and_test` | `or_test` "or" `and_test`
1178 and_test: `not_test` | `and_test` "and" `not_test`
1179 not_test: `comparison` | "not" `not_test`
1180
1181In the context of Boolean operations, and also when expressions are used by
1182control flow statements, the following values are interpreted as false:
1183``False``, ``None``, numeric zero of all types, and empty strings and containers
1184(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001185other values are interpreted as true. User-defined objects can customize their
1186truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001187
1188.. index:: operator: not
1189
1190The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1191otherwise.
1192
Georg Brandl116aa622007-08-15 14:28:22 +00001193.. index:: operator: and
1194
1195The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1196returned; otherwise, *y* is evaluated and the resulting value is returned.
1197
1198.. index:: operator: or
1199
1200The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1201returned; otherwise, *y* is evaluated and the resulting value is returned.
1202
1203(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1204they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001205argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001206replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1207the desired value. Because :keyword:`not` has to invent a value anyway, it does
1208not bother to return a value of the same type as its argument, so e.g., ``not
1209'foo'`` yields ``False``, not ``''``.)
1210
1211
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001212Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001213=======================
1214
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001215.. index::
1216 pair: conditional; expression
1217 pair: ternary; operator
1218
1219.. productionlist::
1220 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1221 expression: `conditional_expression` | `lambda_form`
1222 expression_nocond: `or_test` | `lambda_form_nocond`
1223
1224Conditional expressions (sometimes called a "ternary operator") have the lowest
1225priority of all Python operations.
1226
1227The expression ``x if C else y`` first evaluates the condition, *C* (*not* *x*);
1228if *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
1229evaluated and its value is returned.
1230
1231See :pep:`308` for more details about conditional expressions.
1232
1233
Georg Brandl116aa622007-08-15 14:28:22 +00001234.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001235.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001236
1237Lambdas
1238=======
1239
1240.. index::
1241 pair: lambda; expression
1242 pair: lambda; form
1243 pair: anonymous; function
1244
1245.. productionlist::
1246 lambda_form: "lambda" [`parameter_list`]: `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +00001247 lambda_form_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001248
1249Lambda forms (lambda expressions) have the same syntactic position as
1250expressions. They are a shorthand to create anonymous functions; the expression
1251``lambda arguments: expression`` yields a function object. The unnamed object
1252behaves like a function object defined with ::
1253
Georg Brandl96593ed2007-09-07 14:15:41 +00001254 def <lambda>(arguments):
Georg Brandl116aa622007-08-15 14:28:22 +00001255 return expression
1256
1257See section :ref:`function` for the syntax of parameter lists. Note that
1258functions created with lambda forms cannot contain statements or annotations.
1259
Georg Brandl116aa622007-08-15 14:28:22 +00001260
1261.. _exprlists:
1262
1263Expression lists
1264================
1265
1266.. index:: pair: expression; list
1267
1268.. productionlist::
1269 expression_list: `expression` ( "," `expression` )* [","]
1270
1271.. index:: object: tuple
1272
1273An expression list containing at least one comma yields a tuple. The length of
1274the tuple is the number of expressions in the list. The expressions are
1275evaluated from left to right.
1276
1277.. index:: pair: trailing; comma
1278
1279The trailing comma is required only to create a single tuple (a.k.a. a
1280*singleton*); it is optional in all other cases. A single expression without a
1281trailing comma doesn't create a tuple, but rather yields the value of that
1282expression. (To create an empty tuple, use an empty pair of parentheses:
1283``()``.)
1284
1285
1286.. _evalorder:
1287
1288Evaluation order
1289================
1290
1291.. index:: pair: evaluation; order
1292
Georg Brandl96593ed2007-09-07 14:15:41 +00001293Python evaluates expressions from left to right. Notice that while evaluating
1294an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001295
1296In the following lines, expressions will be evaluated in the arithmetic order of
1297their suffixes::
1298
1299 expr1, expr2, expr3, expr4
1300 (expr1, expr2, expr3, expr4)
1301 {expr1: expr2, expr3: expr4}
1302 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001303 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001304 expr3, expr4 = expr1, expr2
1305
1306
1307.. _operator-summary:
1308
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001309Operator precedence
1310===================
Georg Brandl116aa622007-08-15 14:28:22 +00001311
1312.. index:: pair: operator; precedence
1313
1314The following table summarizes the operator precedences in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001315precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001316the same box have the same precedence. Unless the syntax is explicitly given,
1317operators are binary. Operators in the same box group left to right (except for
1318comparisons, including tests, which all have the same precedence and chain from
1319left to right --- see section :ref:`comparisons` --- and exponentiation, which
1320groups from right to left).
1321
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001322
1323+-----------------------------------------------+-------------------------------------+
1324| Operator | Description |
1325+===============================================+=====================================+
1326| :keyword:`lambda` | Lambda expression |
1327+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001328| :keyword:`if` -- :keyword:`else` | Conditional expression |
1329+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001330| :keyword:`or` | Boolean OR |
1331+-----------------------------------------------+-------------------------------------+
1332| :keyword:`and` | Boolean AND |
1333+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001334| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001335+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001336| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001337| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandla5ebc262009-06-03 07:26:22 +00001338| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001339+-----------------------------------------------+-------------------------------------+
1340| ``|`` | Bitwise OR |
1341+-----------------------------------------------+-------------------------------------+
1342| ``^`` | Bitwise XOR |
1343+-----------------------------------------------+-------------------------------------+
1344| ``&`` | Bitwise AND |
1345+-----------------------------------------------+-------------------------------------+
1346| ``<<``, ``>>`` | Shifts |
1347+-----------------------------------------------+-------------------------------------+
1348| ``+``, ``-`` | Addition and subtraction |
1349+-----------------------------------------------+-------------------------------------+
1350| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandlf1d633c2010-09-20 06:29:01 +00001351| | [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001352+-----------------------------------------------+-------------------------------------+
1353| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1354+-----------------------------------------------+-------------------------------------+
1355| ``**`` | Exponentiation [#]_ |
1356+-----------------------------------------------+-------------------------------------+
1357| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1358| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1359+-----------------------------------------------+-------------------------------------+
1360| ``(expressions...)``, | Binding or tuple display, |
1361| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001362| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001363| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001364+-----------------------------------------------+-------------------------------------+
1365
Georg Brandl116aa622007-08-15 14:28:22 +00001366
1367.. rubric:: Footnotes
1368
Georg Brandl116aa622007-08-15 14:28:22 +00001369.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1370 true numerically due to roundoff. For example, and assuming a platform on which
1371 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1372 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001373 1e100``, which is numerically exactly equal to ``1e100``. The function
1374 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001375 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1376 is more appropriate depends on the application.
1377
1378.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001379 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001380 cases, Python returns the latter result, in order to preserve that
1381 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1382
Georg Brandl96593ed2007-09-07 14:15:41 +00001383.. [#] While comparisons between strings make sense at the byte level, they may
1384 be counter-intuitive to users. For example, the strings ``"\u00C7"`` and
1385 ``"\u0327\u0043"`` compare differently, even though they both represent the
Georg Brandlae2dbe22009-03-13 19:04:40 +00001386 same unicode character (LATIN CAPITAL LETTER C WITH CEDILLA). To compare
Georg Brandl9afde1c2007-11-01 20:32:30 +00001387 strings in a human recognizable way, compare using
1388 :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001389
Georg Brandl48310cd2009-01-03 21:18:54 +00001390.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001391 descriptors, you may notice seemingly unusual behaviour in certain uses of
1392 the :keyword:`is` operator, like those involving comparisons between instance
1393 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001394
Georg Brandl063f2372010-12-01 15:32:43 +00001395.. [#] The ``%`` operator is also used for string formatting; the same
1396 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001397
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001398.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1399 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.