blob: 380d265be99da5f9df95bfc59a5522cfd4859dd3 [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
10This chapter explains the meaning of the elements of expressions in Python.
11
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
Georg Brandl96593ed2007-09-07 14:15:41 +0000119With the exception of bytes literals, these all correspond to immutable data
120types, and hence the object's identity is less important than its value.
121Multiple evaluations of literals with the same value (either the same occurrence
122in the program text or a different occurrence) may obtain the same object or a
123different object with the same value.
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 Brandl96593ed2007-09-07 14:15:41 +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
234
235.. _dict:
236
237Dictionary displays
238-------------------
239
240.. index:: pair: dictionary; display
Georg Brandl96593ed2007-09-07 14:15:41 +0000241 key, datum, key/datum pair
242 object: dictionary
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244A dictionary display is a possibly empty series of key/datum pairs enclosed in
245curly braces:
246
247.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000248 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000249 key_datum_list: `key_datum` ("," `key_datum`)* [","]
250 key_datum: `expression` ":" `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +0000251 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000252
253A dictionary display yields a new dictionary object.
254
Georg Brandl96593ed2007-09-07 14:15:41 +0000255If a comma-separated sequence of key/datum pairs is given, they are evaluated
256from left to right to define the entries of the dictionary: each key object is
257used as a key into the dictionary to store the corresponding datum. This means
258that you can specify the same key multiple times in the key/datum list, and the
259final dictionary's value for that key will be the last one given.
260
261A dict comprehension, in contrast to list and set comprehensions, needs two
262expressions separated with a colon followed by the usual "for" and "if" clauses.
263When the comprehension is run, the resulting key and value elements are inserted
264in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000267 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000268
269Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000270:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000271all mutable objects.) Clashes between duplicate keys are not detected; the last
272datum (textually rightmost in the display) stored for a given key value
273prevails.
274
275
Georg Brandl96593ed2007-09-07 14:15:41 +0000276.. _genexpr:
277
278Generator expressions
279---------------------
280
281.. index:: pair: generator; expression
282 object: generator
283
284A generator expression is a compact generator notation in parentheses:
285
286.. productionlist::
287 generator_expression: "(" `expression` `comp_for` ")"
288
289A generator expression yields a new generator object. Its syntax is the same as
290for comprehensions, except that it is enclosed in parentheses instead of
291brackets or curly braces.
292
293Variables used in the generator expression are evaluated lazily when the
294:meth:`__next__` method is called for generator object (in the same fashion as
295normal generators). However, the leftmost :keyword:`for` clause is immediately
296evaluated, so that an error produced by it can be seen before any other possible
297error in the code that handles the generator expression. Subsequent
298:keyword:`for` clauses cannot be evaluated immediately since they may depend on
299the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y
300in bar(x))``.
301
302The parentheses can be omitted on calls with only one argument. See section
303:ref:`calls` for the detail.
304
305
Georg Brandl116aa622007-08-15 14:28:22 +0000306.. _yieldexpr:
307
308Yield expressions
309-----------------
310
311.. index::
312 keyword: yield
313 pair: yield; expression
314 pair: generator; function
315
316.. productionlist::
317 yield_atom: "(" `yield_expression` ")"
318 yield_expression: "yield" [`expression_list`]
319
Georg Brandl116aa622007-08-15 14:28:22 +0000320The :keyword:`yield` expression is only used when defining a generator function,
Georg Brandl96593ed2007-09-07 14:15:41 +0000321and can only be used in the body of a function definition. Using a
Georg Brandl116aa622007-08-15 14:28:22 +0000322:keyword:`yield` expression in a function definition is sufficient to cause that
323definition to create a generator function instead of a normal function.
324
325When a generator function is called, it returns an iterator known as a
326generator. That generator then controls the execution of a generator function.
327The execution starts when one of the generator's methods is called. At that
328time, the execution proceeds to the first :keyword:`yield` expression, where it
329is suspended again, returning the value of :token:`expression_list` to
330generator's caller. By suspended we mean that all local state is retained,
331including the current bindings of local variables, the instruction pointer, and
332the internal evaluation stack. When the execution is resumed by calling one of
333the generator's methods, the function can proceed exactly as if the
Georg Brandl96593ed2007-09-07 14:15:41 +0000334:keyword:`yield` expression was just another external call. The value of the
Georg Brandl116aa622007-08-15 14:28:22 +0000335:keyword:`yield` expression after resuming depends on the method which resumed
336the execution.
337
338.. index:: single: coroutine
339
340All of this makes generator functions quite similar to coroutines; they yield
341multiple times, they have more than one entry point and their execution can be
342suspended. The only difference is that a generator function cannot control
343where should the execution continue after it yields; the control is always
344transfered to the generator's caller.
345
Georg Brandl02c30562007-09-07 17:52:53 +0000346The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a
347:keyword:`try` ... :keyword:`finally` construct. If the generator is not
348resumed before it is finalized (by reaching a zero reference count or by being
349garbage collected), the generator-iterator's :meth:`close` method will be
350called, allowing any pending :keyword:`finally` clauses to execute.
351
Georg Brandl116aa622007-08-15 14:28:22 +0000352.. index:: object: generator
353
354The following generator's methods can be used to control the execution of a
355generator function:
356
357.. index:: exception: StopIteration
358
359
Georg Brandl96593ed2007-09-07 14:15:41 +0000360.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000361
Georg Brandl96593ed2007-09-07 14:15:41 +0000362 Starts the execution of a generator function or resumes it at the last
363 executed :keyword:`yield` expression. When a generator function is resumed
364 with a :meth:`next` method, the current :keyword:`yield` expression always
365 evaluates to :const:`None`. The execution then continues to the next
366 :keyword:`yield` expression, where the generator is suspended again, and the
367 value of the :token:`expression_list` is returned to :meth:`next`'s caller.
368 If the generator exits without yielding another value, a :exc:`StopIteration`
369 exception is raised.
370
371 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
372 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374
375.. method:: generator.send(value)
376
377 Resumes the execution and "sends" a value into the generator function. The
378 ``value`` argument becomes the result of the current :keyword:`yield`
379 expression. The :meth:`send` method returns the next value yielded by the
380 generator, or raises :exc:`StopIteration` if the generator exits without
Georg Brandl96593ed2007-09-07 14:15:41 +0000381 yielding another value. When :meth:`send` is called to start the generator,
382 it must be called with :const:`None` as the argument, because there is no
Georg Brandl116aa622007-08-15 14:28:22 +0000383 :keyword:`yield` expression that could receieve the value.
384
385
386.. method:: generator.throw(type[, value[, traceback]])
387
388 Raises an exception of type ``type`` at the point where generator was paused,
389 and returns the next value yielded by the generator function. If the generator
390 exits without yielding another value, a :exc:`StopIteration` exception is
391 raised. If the generator function does not catch the passed-in exception, or
392 raises a different exception, then that exception propagates to the caller.
393
394.. index:: exception: GeneratorExit
395
396
397.. method:: generator.close()
398
399 Raises a :exc:`GeneratorExit` at the point where the generator function was
Georg Brandl96593ed2007-09-07 14:15:41 +0000400 paused. If the generator function then raises :exc:`StopIteration` (by
401 exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by
402 not catching the exception), close returns to its caller. If the generator
403 yields a value, a :exc:`RuntimeError` is raised. If the generator raises any
404 other exception, it is propagated to the caller. :meth:`close` does nothing
405 if the generator has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407Here is a simple example that demonstrates the behavior of generators and
408generator functions::
409
410 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000411 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000412 ... try:
413 ... while True:
414 ... try:
415 ... value = (yield value)
Georg Brandl116aa622007-08-15 14:28:22 +0000416 ... except Exception, e:
417 ... value = e
418 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000419 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000420 ...
421 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000422 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000423 Execution starts when 'next()' is called for the first time.
424 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000425 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000426 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000427 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000428 2
429 >>> generator.throw(TypeError, "spam")
430 TypeError('spam',)
431 >>> generator.close()
432 Don't forget to clean up when 'close()' is called.
433
434
435.. seealso::
436
Georg Brandl02c30562007-09-07 17:52:53 +0000437 :pep:`0255` - Simple Generators
438 The proposal for adding generators and the :keyword:`yield` statement to Python.
439
Georg Brandl116aa622007-08-15 14:28:22 +0000440 :pep:`0342` - Coroutines via Enhanced Generators
Georg Brandl96593ed2007-09-07 14:15:41 +0000441 The proposal to enhance the API and syntax of generators, making them
442 usable as simple coroutines.
Georg Brandl116aa622007-08-15 14:28:22 +0000443
444
445.. _primaries:
446
447Primaries
448=========
449
450.. index:: single: primary
451
452Primaries represent the most tightly bound operations of the language. Their
453syntax is:
454
455.. productionlist::
456 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
457
458
459.. _attribute-references:
460
461Attribute references
462--------------------
463
464.. index:: pair: attribute; reference
465
466An attribute reference is a primary followed by a period and a name:
467
468.. productionlist::
469 attributeref: `primary` "." `identifier`
470
471.. index::
472 exception: AttributeError
473 object: module
474 object: list
475
476The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000477references, which most objects do. This object is then asked to produce the
478attribute whose name is the identifier (which can be customized by overriding
479the :meth:`__getattr__` method). If this attribute is not available, the
480exception :exc:`AttributeError` is raised. Otherwise, the type and value of the
481object produced is determined by the object. Multiple evaluations of the same
482attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484
485.. _subscriptions:
486
487Subscriptions
488-------------
489
490.. index:: single: subscription
491
492.. index::
493 object: sequence
494 object: mapping
495 object: string
496 object: tuple
497 object: list
498 object: dictionary
499 pair: sequence; item
500
501A subscription selects an item of a sequence (string, tuple or list) or mapping
502(dictionary) object:
503
504.. productionlist::
505 subscription: `primary` "[" `expression_list` "]"
506
Georg Brandl96593ed2007-09-07 14:15:41 +0000507The primary must evaluate to an object that supports subscription, e.g. a list
508or dictionary. User-defined objects can support subscription by defining a
509:meth:`__getitem__` method.
510
511For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000512
513If the primary is a mapping, the expression list must evaluate to an object
514whose value is one of the keys of the mapping, and the subscription selects the
515value in the mapping that corresponds to that key. (The expression list is a
516tuple except if it has exactly one item.)
517
Georg Brandl96593ed2007-09-07 14:15:41 +0000518If the primary is a sequence, the expression (list) must evaluate to an integer.
519If this value is negative, the length of the sequence is added to it (so that,
520e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value must be a
521nonnegative integer less than the number of items in the sequence, and the
522subscription selects the item whose index is that value (counting from zero).
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524.. index::
525 single: character
526 pair: string; item
527
528A string's items are characters. A character is not a separate data type but a
529string of exactly one character.
530
531
532.. _slicings:
533
534Slicings
535--------
536
537.. index::
538 single: slicing
539 single: slice
540
541.. index::
542 object: sequence
543 object: string
544 object: tuple
545 object: list
546
547A slicing selects a range of items in a sequence object (e.g., a string, tuple
548or list). Slicings may be used as expressions or as targets in assignment or
549:keyword:`del` statements. The syntax for a slicing:
550
551.. productionlist::
Thomas Wouters53de1902007-09-04 09:03:59 +0000552 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000553 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000554 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000555 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000556 lower_bound: `expression`
557 upper_bound: `expression`
558 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000559
560There is ambiguity in the formal syntax here: anything that looks like an
561expression list also looks like a slice list, so any subscription can be
562interpreted as a slicing. Rather than further complicating the syntax, this is
563disambiguated by defining that in this case the interpretation as a subscription
564takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000565slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000566
567.. index::
568 single: start (slice object attribute)
569 single: stop (slice object attribute)
570 single: step (slice object attribute)
571
Thomas Wouters53de1902007-09-04 09:03:59 +0000572The semantics for a slicing are as follows. The primary must evaluate to a
Georg Brandl96593ed2007-09-07 14:15:41 +0000573mapping object, and it is indexed (using the same :meth:`__getitem__` method as
574normal subscription) with a key that is constructed from the slice list, as
575follows. If the slice list contains at least one comma, the key is a tuple
576containing the conversion of the slice items; otherwise, the conversion of the
577lone slice item is the key. The conversion of a slice item that is an
578expression is that expression. The conversion of a proper slice is a slice
579object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
580:attr:`step` attributes are the values of the expressions given as lower bound,
581upper bound and stride, respectively, substituting ``None`` for missing
582expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000583
584
585.. _calls:
586
587Calls
588-----
589
590.. index:: single: call
591
592.. index:: object: callable
593
594A call calls a callable object (e.g., a function) with a possibly empty series
595of arguments:
596
597.. productionlist::
598 call: `primary` "(" [`argument_list` [","]
599 : | `expression` `genexpr_for`] ")"
600 argument_list: `positional_arguments` ["," `keyword_arguments`]
601 : ["," "*" `expression`]
602 : ["," "**" `expression`]
603 : | `keyword_arguments` ["," "*" `expression`]
604 : ["," "**" `expression`]
605 : | "*" `expression` ["," "**" `expression`]
606 : | "**" `expression`
607 positional_arguments: `expression` ("," `expression`)*
608 keyword_arguments: `keyword_item` ("," `keyword_item`)*
609 keyword_item: `identifier` "=" `expression`
610
611A trailing comma may be present after the positional and keyword arguments but
612does not affect the semantics.
613
614The primary must evaluate to a callable object (user-defined functions, built-in
615functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000616instances, and all objects having a :meth:`__call__` method are callable). All
617argument expressions are evaluated before the call is attempted. Please refer
618to section :ref:`function` for the syntax of formal parameter lists.
619
620.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000621
622If keyword arguments are present, they are first converted to positional
623arguments, as follows. First, a list of unfilled slots is created for the
624formal parameters. If there are N positional arguments, they are placed in the
625first N slots. Next, for each keyword argument, the identifier is used to
626determine the corresponding slot (if the identifier is the same as the first
627formal parameter name, the first slot is used, and so on). If the slot is
628already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
629the argument is placed in the slot, filling it (even if the expression is
630``None``, it fills the slot). When all arguments have been processed, the slots
631that are still unfilled are filled with the corresponding default value from the
632function definition. (Default values are calculated, once, when the function is
633defined; thus, a mutable object such as a list or dictionary used as default
634value will be shared by all calls that don't specify an argument value for the
635corresponding slot; this should usually be avoided.) If there are any unfilled
636slots for which no default value is specified, a :exc:`TypeError` exception is
637raised. Otherwise, the list of filled slots is used as the argument list for
638the call.
639
640If there are more positional arguments than there are formal parameter slots, a
641:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
642``*identifier`` is present; in this case, that formal parameter receives a tuple
643containing the excess positional arguments (or an empty tuple if there were no
644excess positional arguments).
645
646If any keyword argument does not correspond to a formal parameter name, a
647:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
648``**identifier`` is present; in this case, that formal parameter receives a
649dictionary containing the excess keyword arguments (using the keywords as keys
650and the argument values as corresponding values), or a (new) empty dictionary if
651there were no excess keyword arguments.
652
653If the syntax ``*expression`` appears in the function call, ``expression`` must
654evaluate to a sequence. Elements from this sequence are treated as if they were
655additional positional arguments; if there are postional arguments *x1*,...,*xN*
656, and ``expression`` evaluates to a sequence *y1*,...,*yM*, this is equivalent
657to a call with M+N positional arguments *x1*,...,*xN*,*y1*,...,*yM*.
658
659A consequence of this is that although the ``*expression`` syntax appears
660*after* any keyword arguments, it is processed *before* the keyword arguments
661(and the ``**expression`` argument, if any -- see below). So::
662
663 >>> def f(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000664 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000665 ...
666 >>> f(b=1, *(2,))
667 2 1
668 >>> f(a=1, *(2,))
669 Traceback (most recent call last):
670 File "<stdin>", line 1, in ?
671 TypeError: f() got multiple values for keyword argument 'a'
672 >>> f(1, *(2,))
673 1 2
674
675It is unusual for both keyword arguments and the ``*expression`` syntax to be
676used in the same call, so in practice this confusion does not arise.
677
678If the syntax ``**expression`` appears in the function call, ``expression`` must
679evaluate to a mapping, the contents of which are treated as additional keyword
680arguments. In the case of a keyword appearing in both ``expression`` and as an
681explicit keyword argument, a :exc:`TypeError` exception is raised.
682
683Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
684used as positional argument slots or as keyword argument names.
685
686A call always returns some value, possibly ``None``, unless it raises an
687exception. How this value is computed depends on the type of the callable
688object.
689
690If it is---
691
692a user-defined function:
693 .. index::
694 pair: function; call
695 triple: user-defined; function; call
696 object: user-defined function
697 object: function
698
699 The code block for the function is executed, passing it the argument list. The
700 first thing the code block will do is bind the formal parameters to the
701 arguments; this is described in section :ref:`function`. When the code block
702 executes a :keyword:`return` statement, this specifies the return value of the
703 function call.
704
705a built-in function or method:
706 .. index::
707 pair: function; call
708 pair: built-in function; call
709 pair: method; call
710 pair: built-in method; call
711 object: built-in method
712 object: built-in function
713 object: method
714 object: function
715
716 The result is up to the interpreter; see :ref:`built-in-funcs` for the
717 descriptions of built-in functions and methods.
718
719a class object:
720 .. index::
721 object: class
722 pair: class object; call
723
724 A new instance of that class is returned.
725
726a class instance method:
727 .. index::
728 object: class instance
729 object: instance
730 pair: class instance; call
731
732 The corresponding user-defined function is called, with an argument list that is
733 one longer than the argument list of the call: the instance becomes the first
734 argument.
735
736a class instance:
737 .. index::
738 pair: instance; call
739 single: __call__() (object method)
740
741 The class must define a :meth:`__call__` method; the effect is then the same as
742 if that method was called.
743
744
745.. _power:
746
747The power operator
748==================
749
750The power operator binds more tightly than unary operators on its left; it binds
751less tightly than unary operators on its right. The syntax is:
752
753.. productionlist::
754 power: `primary` ["**" `u_expr`]
755
756Thus, in an unparenthesized sequence of power and unary operators, the operators
757are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +0000758for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000759
760The power operator has the same semantics as the built-in :func:`pow` function,
761when called with two arguments: it yields its left argument raised to the power
762of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +0000763type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +0000764
Georg Brandl96593ed2007-09-07 14:15:41 +0000765For int operands, the result has the same type as the operands unless the second
766argument is negative; in that case, all arguments are converted to float and a
767float result is delivered. For example, ``10**2`` returns ``100``, but
768``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +0000769
770Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +0000771Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +0000772number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774
775.. _unary:
776
777Unary arithmetic operations
778===========================
779
780.. index::
781 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +0000782 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000783
Christian Heimesfaf2f632008-01-06 16:59:19 +0000784All unary arithmetic (and bitwise) operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +0000785
786.. productionlist::
787 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
788
789.. index::
790 single: negation
791 single: minus
792
793The unary ``-`` (minus) operator yields the negation of its numeric argument.
794
795.. index:: single: plus
796
797The unary ``+`` (plus) operator yields its numeric argument unchanged.
798
799.. index:: single: inversion
800
Christian Heimesfaf2f632008-01-06 16:59:19 +0000801
802The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
803long integer argument. The bitwise inversion of ``x`` is defined as
804``-(x+1)``. It only applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000805
806.. index:: exception: TypeError
807
808In all three cases, if the argument does not have the proper type, a
809:exc:`TypeError` exception is raised.
810
811
812.. _binary:
813
814Binary arithmetic operations
815============================
816
817.. index:: triple: binary; arithmetic; operation
818
819The binary arithmetic operations have the conventional priority levels. Note
820that some of these operations also apply to certain non-numeric types. Apart
821from the power operator, there are only two levels, one for multiplicative
822operators and one for additive operators:
823
824.. productionlist::
825 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
826 : | `m_expr` "%" `u_expr`
827 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
828
829.. index:: single: multiplication
830
831The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +0000832arguments must either both be numbers, or one argument must be an integer and
833the other must be a sequence. In the former case, the numbers are converted to a
834common type and then multiplied together. In the latter case, sequence
835repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000836
837.. index::
838 exception: ZeroDivisionError
839 single: division
840
841The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
842their arguments. The numeric arguments are first converted to a common type.
Georg Brandl96593ed2007-09-07 14:15:41 +0000843Integer division yields a float, while floor division of integers results in an
844integer; the result is that of mathematical division with the 'floor' function
845applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
846exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000847
848.. index:: single: modulo
849
850The ``%`` (modulo) operator yields the remainder from the division of the first
851argument by the second. The numeric arguments are first converted to a common
852type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
853arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
854(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
855result with the same sign as its second operand (or zero); the absolute value of
856the result is strictly smaller than the absolute value of the second operand
857[#]_.
858
Georg Brandl96593ed2007-09-07 14:15:41 +0000859The floor division and modulo operators are connected by the following
860identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
861connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
862x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000863
864In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +0000865also overloaded by string objects to perform old-style string formatting (also
866known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +0000867Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +0000868
869The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +0000870function are not defined for complex numbers. Instead, convert to a floating
871point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +0000872
873.. index:: single: addition
874
Georg Brandl96593ed2007-09-07 14:15:41 +0000875The ``+`` (addition) operator yields the sum of its arguments. The arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000876must either both be numbers or both sequences of the same type. In the former
877case, the numbers are converted to a common type and then added together. In
878the latter case, the sequences are concatenated.
879
880.. index:: single: subtraction
881
882The ``-`` (subtraction) operator yields the difference of its arguments. The
883numeric arguments are first converted to a common type.
884
885
886.. _shifting:
887
888Shifting operations
889===================
890
891.. index:: pair: shifting; operation
892
893The shifting operations have lower priority than the arithmetic operations:
894
895.. productionlist::
896 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
897
Georg Brandl96593ed2007-09-07 14:15:41 +0000898These operators accept integers as arguments. They shift the first argument to
899the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000900
901.. index:: exception: ValueError
902
903A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift
Georg Brandl96593ed2007-09-07 14:15:41 +0000904by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000905
906
907.. _bitwise:
908
Christian Heimesfaf2f632008-01-06 16:59:19 +0000909Binary bitwise operations
910=========================
Georg Brandl116aa622007-08-15 14:28:22 +0000911
Christian Heimesfaf2f632008-01-06 16:59:19 +0000912.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000913
914Each of the three bitwise operations has a different priority level:
915
916.. productionlist::
917 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
918 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
919 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
920
Christian Heimesfaf2f632008-01-06 16:59:19 +0000921.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +0000922
Georg Brandl96593ed2007-09-07 14:15:41 +0000923The ``&`` operator yields the bitwise AND of its arguments, which must be
924integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000925
926.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000927 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +0000928 pair: exclusive; or
929
930The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +0000931must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000932
933.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000934 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +0000935 pair: inclusive; or
936
937The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +0000938must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000939
940
941.. _comparisons:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000942.. _is:
943.. _isnot:
944.. _in:
945.. _notin:
Georg Brandl116aa622007-08-15 14:28:22 +0000946
947Comparisons
948===========
949
950.. index:: single: comparison
951
952.. index:: pair: C; language
953
954Unlike C, all comparison operations in Python have the same priority, which is
955lower than that of any arithmetic, shifting or bitwise operation. Also unlike
956C, expressions like ``a < b < c`` have the interpretation that is conventional
957in mathematics:
958
959.. productionlist::
960 comparison: `or_expr` ( `comp_operator` `or_expr` )*
961 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
962 : | "is" ["not"] | ["not"] "in"
963
964Comparisons yield boolean values: ``True`` or ``False``.
965
966.. index:: pair: chaining; comparisons
967
968Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
969``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
970cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
971
Guido van Rossum04110fb2007-08-24 16:32:05 +0000972Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
973*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
974to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
975evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +0000976
Guido van Rossum04110fb2007-08-24 16:32:05 +0000977Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +0000978*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
979pretty).
980
981The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
982values of two objects. The objects need not have the same type. If both are
983numbers, they are converted to a common type. Otherwise, objects of different
984types *always* compare unequal, and are ordered consistently but arbitrarily.
985You can control comparison behavior of objects of non-builtin types by defining
Georg Brandl96593ed2007-09-07 14:15:41 +0000986a :meth:`__cmp__` method or rich comparison methods like :meth:`__gt__`,
987described in section :ref:`specialnames`.
Georg Brandl116aa622007-08-15 14:28:22 +0000988
989(This unusual definition of comparison was used to simplify the definition of
990operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
991In the future, the comparison rules for objects of different types are likely to
992change.)
993
994Comparison of objects of the same type depends on the type:
995
996* Numbers are compared arithmetically.
997
Georg Brandl96593ed2007-09-07 14:15:41 +0000998* Bytes objects are compared lexicographically using the numeric values of their
999 elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001000
Georg Brandl116aa622007-08-15 14:28:22 +00001001* Strings are compared lexicographically using the numeric equivalents (the
Georg Brandl96593ed2007-09-07 14:15:41 +00001002 result of the built-in function :func:`ord`) of their characters. [#]_ String
1003 and bytes object can't be compared!
Georg Brandl116aa622007-08-15 14:28:22 +00001004
1005* Tuples and lists are compared lexicographically using comparison of
1006 corresponding elements. This means that to compare equal, each element must
1007 compare equal and the two sequences must be of the same type and have the same
1008 length.
1009
1010 If not equal, the sequences are ordered the same as their first differing
1011 elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
Georg Brandl96593ed2007-09-07 14:15:41 +00001012 ``cmp(x,y)``. If the corresponding element does not exist, the shorter
1013 sequence is ordered first (for example, ``[1,2] < [1,2,3]``).
Georg Brandl116aa622007-08-15 14:28:22 +00001014
Georg Brandl96593ed2007-09-07 14:15:41 +00001015* Mappings (dictionaries) compare equal if and only if their sorted ``(key,
1016 value)`` lists compare equal. [#]_ Outcomes other than equality are resolved
Georg Brandl116aa622007-08-15 14:28:22 +00001017 consistently, but are not otherwise defined. [#]_
1018
1019* Most other objects of builtin types compare unequal unless they are the same
1020 object; the choice whether one object is considered smaller or larger than
1021 another one is made arbitrarily but consistently within one execution of a
1022 program.
1023
Georg Brandl96593ed2007-09-07 14:15:41 +00001024The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
1025s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not
1026in s`` returns the negation of ``x in s``. All built-in sequences and set types
1027support this as well as dictionary, for which :keyword:`in` tests whether a the
1028dictionary has a given key.
Georg Brandl116aa622007-08-15 14:28:22 +00001029
1030For the list and tuple types, ``x in y`` is true if and only if there exists an
1031index *i* such that ``x == y[i]`` is true.
1032
Georg Brandl4b491312007-08-31 09:22:56 +00001033For the string and bytes types, ``x in y`` is true if and only if *x* is a
1034substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1035always considered to be a substring of any other string, so ``"" in "abc"`` will
1036return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001037
Georg Brandl116aa622007-08-15 14:28:22 +00001038For user-defined classes which define the :meth:`__contains__` method, ``x in
1039y`` is true if and only if ``y.__contains__(x)`` is true.
1040
1041For user-defined classes which do not define :meth:`__contains__` and do define
1042:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1043integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001044raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001045if :keyword:`in` raised that exception).
1046
1047.. index::
1048 operator: in
1049 operator: not in
1050 pair: membership; test
1051 object: sequence
1052
1053The operator :keyword:`not in` is defined to have the inverse true value of
1054:keyword:`in`.
1055
1056.. index::
1057 operator: is
1058 operator: is not
1059 pair: identity; test
1060
1061The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1062is y`` is true if and only if *x* and *y* are the same object. ``x is not y``
1063yields the inverse truth value.
1064
1065
1066.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001067.. _and:
1068.. _or:
1069.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001070
1071Boolean operations
1072==================
1073
1074.. index::
1075 pair: Conditional; expression
1076 pair: Boolean; operation
1077
1078Boolean operations have the lowest priority of all Python operations:
1079
1080.. productionlist::
1081 expression: `conditional_expression` | `lambda_form`
Georg Brandl96593ed2007-09-07 14:15:41 +00001082 expression_nocond: `or_test` | `lambda_form_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001083 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1084 or_test: `and_test` | `or_test` "or" `and_test`
1085 and_test: `not_test` | `and_test` "and" `not_test`
1086 not_test: `comparison` | "not" `not_test`
1087
1088In the context of Boolean operations, and also when expressions are used by
1089control flow statements, the following values are interpreted as false:
1090``False``, ``None``, numeric zero of all types, and empty strings and containers
1091(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001092other values are interpreted as true. User-defined objects can customize their
1093truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001094
1095.. index:: operator: not
1096
1097The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1098otherwise.
1099
1100The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is
1101true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated
1102and its value is returned.
1103
Georg Brandl116aa622007-08-15 14:28:22 +00001104.. index:: operator: and
1105
1106The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1107returned; otherwise, *y* is evaluated and the resulting value is returned.
1108
1109.. index:: operator: or
1110
1111The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1112returned; otherwise, *y* is evaluated and the resulting value is returned.
1113
1114(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1115they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001116argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001117replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1118the desired value. Because :keyword:`not` has to invent a value anyway, it does
1119not bother to return a value of the same type as its argument, so e.g., ``not
1120'foo'`` yields ``False``, not ``''``.)
1121
1122
1123.. _lambdas:
1124
1125Lambdas
1126=======
1127
1128.. index::
1129 pair: lambda; expression
1130 pair: lambda; form
1131 pair: anonymous; function
1132
1133.. productionlist::
1134 lambda_form: "lambda" [`parameter_list`]: `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +00001135 lambda_form_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001136
1137Lambda forms (lambda expressions) have the same syntactic position as
1138expressions. They are a shorthand to create anonymous functions; the expression
1139``lambda arguments: expression`` yields a function object. The unnamed object
1140behaves like a function object defined with ::
1141
Georg Brandl96593ed2007-09-07 14:15:41 +00001142 def <lambda>(arguments):
Georg Brandl116aa622007-08-15 14:28:22 +00001143 return expression
1144
1145See section :ref:`function` for the syntax of parameter lists. Note that
1146functions created with lambda forms cannot contain statements or annotations.
1147
1148.. _lambda:
1149
1150
1151.. _exprlists:
1152
1153Expression lists
1154================
1155
1156.. index:: pair: expression; list
1157
1158.. productionlist::
1159 expression_list: `expression` ( "," `expression` )* [","]
1160
1161.. index:: object: tuple
1162
1163An expression list containing at least one comma yields a tuple. The length of
1164the tuple is the number of expressions in the list. The expressions are
1165evaluated from left to right.
1166
1167.. index:: pair: trailing; comma
1168
1169The trailing comma is required only to create a single tuple (a.k.a. a
1170*singleton*); it is optional in all other cases. A single expression without a
1171trailing comma doesn't create a tuple, but rather yields the value of that
1172expression. (To create an empty tuple, use an empty pair of parentheses:
1173``()``.)
1174
1175
1176.. _evalorder:
1177
1178Evaluation order
1179================
1180
1181.. index:: pair: evaluation; order
1182
Georg Brandl96593ed2007-09-07 14:15:41 +00001183Python evaluates expressions from left to right. Notice that while evaluating
1184an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001185
1186In the following lines, expressions will be evaluated in the arithmetic order of
1187their suffixes::
1188
1189 expr1, expr2, expr3, expr4
1190 (expr1, expr2, expr3, expr4)
1191 {expr1: expr2, expr3: expr4}
1192 expr1 + expr2 * (expr3 - expr4)
1193 func(expr1, expr2, *expr3, **expr4)
1194 expr3, expr4 = expr1, expr2
1195
1196
1197.. _operator-summary:
1198
1199Summary
1200=======
1201
1202.. index:: pair: operator; precedence
1203
1204The following table summarizes the operator precedences in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001205precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001206the same box have the same precedence. Unless the syntax is explicitly given,
1207operators are binary. Operators in the same box group left to right (except for
1208comparisons, including tests, which all have the same precedence and chain from
1209left to right --- see section :ref:`comparisons` --- and exponentiation, which
1210groups from right to left).
1211
1212+----------------------------------------------+-------------------------------------+
1213| Operator | Description |
1214+==============================================+=====================================+
1215| :keyword:`lambda` | Lambda expression |
1216+----------------------------------------------+-------------------------------------+
1217| :keyword:`or` | Boolean OR |
1218+----------------------------------------------+-------------------------------------+
1219| :keyword:`and` | Boolean AND |
1220+----------------------------------------------+-------------------------------------+
1221| :keyword:`not` *x* | Boolean NOT |
1222+----------------------------------------------+-------------------------------------+
1223| :keyword:`in`, :keyword:`not` :keyword:`in` | Membership tests |
1224+----------------------------------------------+-------------------------------------+
1225| :keyword:`is`, :keyword:`is not` | Identity tests |
1226+----------------------------------------------+-------------------------------------+
1227| ``<``, ``<=``, ``>``, ``>=``, ``!=``, ``==`` | Comparisons |
1228+----------------------------------------------+-------------------------------------+
1229| ``|`` | Bitwise OR |
1230+----------------------------------------------+-------------------------------------+
1231| ``^`` | Bitwise XOR |
1232+----------------------------------------------+-------------------------------------+
1233| ``&`` | Bitwise AND |
1234+----------------------------------------------+-------------------------------------+
1235| ``<<``, ``>>`` | Shifts |
1236+----------------------------------------------+-------------------------------------+
1237| ``+``, ``-`` | Addition and subtraction |
1238+----------------------------------------------+-------------------------------------+
Georg Brandl96593ed2007-09-07 14:15:41 +00001239| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandl116aa622007-08-15 14:28:22 +00001240+----------------------------------------------+-------------------------------------+
1241| ``+x``, ``-x`` | Positive, negative |
1242+----------------------------------------------+-------------------------------------+
1243| ``~x`` | Bitwise not |
1244+----------------------------------------------+-------------------------------------+
1245| ``**`` | Exponentiation |
1246+----------------------------------------------+-------------------------------------+
1247| ``x.attribute`` | Attribute reference |
1248+----------------------------------------------+-------------------------------------+
1249| ``x[index]`` | Subscription |
1250+----------------------------------------------+-------------------------------------+
1251| ``x[index:index]`` | Slicing |
1252+----------------------------------------------+-------------------------------------+
1253| ``f(arguments...)`` | Function call |
1254+----------------------------------------------+-------------------------------------+
Georg Brandl96593ed2007-09-07 14:15:41 +00001255| ``(expressions...)`` | Binding, tuple display, generator |
1256| | expressions |
Georg Brandl116aa622007-08-15 14:28:22 +00001257+----------------------------------------------+-------------------------------------+
1258| ``[expressions...]`` | List display |
1259+----------------------------------------------+-------------------------------------+
Georg Brandl96593ed2007-09-07 14:15:41 +00001260| ``{expressions...}`` | Dictionary or set display |
Georg Brandl116aa622007-08-15 14:28:22 +00001261+----------------------------------------------+-------------------------------------+
1262
1263.. rubric:: Footnotes
1264
Georg Brandl116aa622007-08-15 14:28:22 +00001265.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1266 true numerically due to roundoff. For example, and assuming a platform on which
1267 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1268 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1269 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod`
1270 in the :mod:`math` module returns a result whose sign matches the sign of the
1271 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1272 is more appropriate depends on the application.
1273
1274.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001275 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001276 cases, Python returns the latter result, in order to preserve that
1277 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1278
Georg Brandl96593ed2007-09-07 14:15:41 +00001279.. [#] While comparisons between strings make sense at the byte level, they may
1280 be counter-intuitive to users. For example, the strings ``"\u00C7"`` and
1281 ``"\u0327\u0043"`` compare differently, even though they both represent the
Georg Brandl9afde1c2007-11-01 20:32:30 +00001282 same unicode character (LATIN CAPTITAL LETTER C WITH CEDILLA). To compare
1283 strings in a human recognizable way, compare using
1284 :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001285
Georg Brandl96593ed2007-09-07 14:15:41 +00001286.. [#] The implementation computes this efficiently, without constructing lists
1287 or sorting.
Georg Brandl116aa622007-08-15 14:28:22 +00001288
1289.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
Georg Brandl96593ed2007-09-07 14:15:41 +00001290 value) lists, but this was very expensive for the common case of comparing
1291 for equality. An even earlier version of Python compared dictionaries by
1292 identity only, but this caused surprises because people expected to be able
1293 to test a dictionary for emptiness by comparing it to ``{}``.
Georg Brandl116aa622007-08-15 14:28:22 +00001294