blob: af79e534c94681000d4cc362f01a85f88a2674d2 [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
Christian Heimes78644762008-03-04 23:39:23 +0000235Variables used in the generator expression are evaluated lazily in a separate
236scope when the :meth:`next` method is called for the generator object (in the
237same fashion as for normal generators). However, the :keyword:`in` expression
238of the leftmost :keyword:`for` clause is immediately evaluated in the current
239scope so that an error produced by it can be seen before any other possible
240error in the code that handles the generator expression. Subsequent
241:keyword:`for` and :keyword:`if` clauses cannot be evaluated immediately since
242they may depend on the previous :keyword:`for` loop. For example:
243``(x*y for x in range(10) for y in bar(x))``.
244
245The parentheses can be omitted on calls with only one argument. See section
246:ref:`calls` for the detail.
247
248
Georg Brandl116aa622007-08-15 14:28:22 +0000249.. _dict:
250
251Dictionary displays
252-------------------
253
254.. index:: pair: dictionary; display
Georg Brandl96593ed2007-09-07 14:15:41 +0000255 key, datum, key/datum pair
256 object: dictionary
Georg Brandl116aa622007-08-15 14:28:22 +0000257
258A dictionary display is a possibly empty series of key/datum pairs enclosed in
259curly braces:
260
261.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000262 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000263 key_datum_list: `key_datum` ("," `key_datum`)* [","]
264 key_datum: `expression` ":" `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +0000265 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267A dictionary display yields a new dictionary object.
268
Georg Brandl96593ed2007-09-07 14:15:41 +0000269If a comma-separated sequence of key/datum pairs is given, they are evaluated
270from left to right to define the entries of the dictionary: each key object is
271used as a key into the dictionary to store the corresponding datum. This means
272that you can specify the same key multiple times in the key/datum list, and the
273final dictionary's value for that key will be the last one given.
274
275A dict comprehension, in contrast to list and set comprehensions, needs two
276expressions separated with a colon followed by the usual "for" and "if" clauses.
277When the comprehension is run, the resulting key and value elements are inserted
278in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000281 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000284:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000285all mutable objects.) Clashes between duplicate keys are not detected; the last
286datum (textually rightmost in the display) stored for a given key value
287prevails.
288
289
Georg Brandl96593ed2007-09-07 14:15:41 +0000290.. _genexpr:
291
292Generator expressions
293---------------------
294
295.. index:: pair: generator; expression
296 object: generator
297
298A generator expression is a compact generator notation in parentheses:
299
300.. productionlist::
301 generator_expression: "(" `expression` `comp_for` ")"
302
303A generator expression yields a new generator object. Its syntax is the same as
304for comprehensions, except that it is enclosed in parentheses instead of
305brackets or curly braces.
306
307Variables used in the generator expression are evaluated lazily when the
308:meth:`__next__` method is called for generator object (in the same fashion as
309normal generators). However, the leftmost :keyword:`for` clause is immediately
310evaluated, so that an error produced by it can be seen before any other possible
311error in the code that handles the generator expression. Subsequent
312:keyword:`for` clauses cannot be evaluated immediately since they may depend on
313the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y
314in bar(x))``.
315
316The parentheses can be omitted on calls with only one argument. See section
317:ref:`calls` for the detail.
318
319
Georg Brandl116aa622007-08-15 14:28:22 +0000320.. _yieldexpr:
321
322Yield expressions
323-----------------
324
325.. index::
326 keyword: yield
327 pair: yield; expression
328 pair: generator; function
329
330.. productionlist::
331 yield_atom: "(" `yield_expression` ")"
332 yield_expression: "yield" [`expression_list`]
333
Georg Brandl116aa622007-08-15 14:28:22 +0000334The :keyword:`yield` expression is only used when defining a generator function,
Georg Brandl96593ed2007-09-07 14:15:41 +0000335and can only be used in the body of a function definition. Using a
Georg Brandl116aa622007-08-15 14:28:22 +0000336:keyword:`yield` expression in a function definition is sufficient to cause that
337definition to create a generator function instead of a normal function.
338
339When a generator function is called, it returns an iterator known as a
340generator. That generator then controls the execution of a generator function.
341The execution starts when one of the generator's methods is called. At that
342time, the execution proceeds to the first :keyword:`yield` expression, where it
343is suspended again, returning the value of :token:`expression_list` to
344generator's caller. By suspended we mean that all local state is retained,
345including the current bindings of local variables, the instruction pointer, and
346the internal evaluation stack. When the execution is resumed by calling one of
347the generator's methods, the function can proceed exactly as if the
Georg Brandl96593ed2007-09-07 14:15:41 +0000348:keyword:`yield` expression was just another external call. The value of the
Georg Brandl116aa622007-08-15 14:28:22 +0000349:keyword:`yield` expression after resuming depends on the method which resumed
350the execution.
351
352.. index:: single: coroutine
353
354All of this makes generator functions quite similar to coroutines; they yield
355multiple times, they have more than one entry point and their execution can be
356suspended. The only difference is that a generator function cannot control
357where should the execution continue after it yields; the control is always
358transfered to the generator's caller.
359
Georg Brandl02c30562007-09-07 17:52:53 +0000360The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a
361:keyword:`try` ... :keyword:`finally` construct. If the generator is not
362resumed before it is finalized (by reaching a zero reference count or by being
363garbage collected), the generator-iterator's :meth:`close` method will be
364called, allowing any pending :keyword:`finally` clauses to execute.
365
Georg Brandl116aa622007-08-15 14:28:22 +0000366.. index:: object: generator
367
368The following generator's methods can be used to control the execution of a
369generator function:
370
371.. index:: exception: StopIteration
372
373
Georg Brandl96593ed2007-09-07 14:15:41 +0000374.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000375
Georg Brandl96593ed2007-09-07 14:15:41 +0000376 Starts the execution of a generator function or resumes it at the last
377 executed :keyword:`yield` expression. When a generator function is resumed
378 with a :meth:`next` method, the current :keyword:`yield` expression always
379 evaluates to :const:`None`. The execution then continues to the next
380 :keyword:`yield` expression, where the generator is suspended again, and the
381 value of the :token:`expression_list` is returned to :meth:`next`'s caller.
382 If the generator exits without yielding another value, a :exc:`StopIteration`
383 exception is raised.
384
385 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
386 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000387
388
389.. method:: generator.send(value)
390
391 Resumes the execution and "sends" a value into the generator function. The
392 ``value`` argument becomes the result of the current :keyword:`yield`
393 expression. The :meth:`send` method returns the next value yielded by the
394 generator, or raises :exc:`StopIteration` if the generator exits without
Georg Brandl96593ed2007-09-07 14:15:41 +0000395 yielding another value. When :meth:`send` is called to start the generator,
396 it must be called with :const:`None` as the argument, because there is no
Christian Heimesc3f30c42008-02-22 16:37:40 +0000397 :keyword:`yield` expression that could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399
400.. method:: generator.throw(type[, value[, traceback]])
401
402 Raises an exception of type ``type`` at the point where generator was paused,
403 and returns the next value yielded by the generator function. If the generator
404 exits without yielding another value, a :exc:`StopIteration` exception is
405 raised. If the generator function does not catch the passed-in exception, or
406 raises a different exception, then that exception propagates to the caller.
407
408.. index:: exception: GeneratorExit
409
410
411.. method:: generator.close()
412
413 Raises a :exc:`GeneratorExit` at the point where the generator function was
Georg Brandl96593ed2007-09-07 14:15:41 +0000414 paused. If the generator function then raises :exc:`StopIteration` (by
415 exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by
416 not catching the exception), close returns to its caller. If the generator
417 yields a value, a :exc:`RuntimeError` is raised. If the generator raises any
418 other exception, it is propagated to the caller. :meth:`close` does nothing
419 if the generator has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421Here is a simple example that demonstrates the behavior of generators and
422generator functions::
423
424 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000425 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000426 ... try:
427 ... while True:
428 ... try:
429 ... value = (yield value)
Georg Brandl116aa622007-08-15 14:28:22 +0000430 ... except Exception, e:
431 ... value = e
432 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000433 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000434 ...
435 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000436 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000437 Execution starts when 'next()' is called for the first time.
438 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000439 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000440 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000441 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000442 2
443 >>> generator.throw(TypeError, "spam")
444 TypeError('spam',)
445 >>> generator.close()
446 Don't forget to clean up when 'close()' is called.
447
448
449.. seealso::
450
Georg Brandl02c30562007-09-07 17:52:53 +0000451 :pep:`0255` - Simple Generators
452 The proposal for adding generators and the :keyword:`yield` statement to Python.
453
Georg Brandl116aa622007-08-15 14:28:22 +0000454 :pep:`0342` - Coroutines via Enhanced Generators
Georg Brandl96593ed2007-09-07 14:15:41 +0000455 The proposal to enhance the API and syntax of generators, making them
456 usable as simple coroutines.
Georg Brandl116aa622007-08-15 14:28:22 +0000457
458
459.. _primaries:
460
461Primaries
462=========
463
464.. index:: single: primary
465
466Primaries represent the most tightly bound operations of the language. Their
467syntax is:
468
469.. productionlist::
470 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
471
472
473.. _attribute-references:
474
475Attribute references
476--------------------
477
478.. index:: pair: attribute; reference
479
480An attribute reference is a primary followed by a period and a name:
481
482.. productionlist::
483 attributeref: `primary` "." `identifier`
484
485.. index::
486 exception: AttributeError
487 object: module
488 object: list
489
490The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000491references, which most objects do. This object is then asked to produce the
492attribute whose name is the identifier (which can be customized by overriding
493the :meth:`__getattr__` method). If this attribute is not available, the
494exception :exc:`AttributeError` is raised. Otherwise, the type and value of the
495object produced is determined by the object. Multiple evaluations of the same
496attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498
499.. _subscriptions:
500
501Subscriptions
502-------------
503
504.. index:: single: subscription
505
506.. index::
507 object: sequence
508 object: mapping
509 object: string
510 object: tuple
511 object: list
512 object: dictionary
513 pair: sequence; item
514
515A subscription selects an item of a sequence (string, tuple or list) or mapping
516(dictionary) object:
517
518.. productionlist::
519 subscription: `primary` "[" `expression_list` "]"
520
Georg Brandl96593ed2007-09-07 14:15:41 +0000521The primary must evaluate to an object that supports subscription, e.g. a list
522or dictionary. User-defined objects can support subscription by defining a
523:meth:`__getitem__` method.
524
525For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000526
527If the primary is a mapping, the expression list must evaluate to an object
528whose value is one of the keys of the mapping, and the subscription selects the
529value in the mapping that corresponds to that key. (The expression list is a
530tuple except if it has exactly one item.)
531
Georg Brandl96593ed2007-09-07 14:15:41 +0000532If the primary is a sequence, the expression (list) must evaluate to an integer.
533If this value is negative, the length of the sequence is added to it (so that,
534e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value must be a
535nonnegative integer less than the number of items in the sequence, and the
536subscription selects the item whose index is that value (counting from zero).
Georg Brandl116aa622007-08-15 14:28:22 +0000537
538.. index::
539 single: character
540 pair: string; item
541
542A string's items are characters. A character is not a separate data type but a
543string of exactly one character.
544
545
546.. _slicings:
547
548Slicings
549--------
550
551.. index::
552 single: slicing
553 single: slice
554
555.. index::
556 object: sequence
557 object: string
558 object: tuple
559 object: list
560
561A slicing selects a range of items in a sequence object (e.g., a string, tuple
562or list). Slicings may be used as expressions or as targets in assignment or
563:keyword:`del` statements. The syntax for a slicing:
564
565.. productionlist::
Thomas Wouters53de1902007-09-04 09:03:59 +0000566 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000567 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000568 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000569 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000570 lower_bound: `expression`
571 upper_bound: `expression`
572 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000573
574There is ambiguity in the formal syntax here: anything that looks like an
575expression list also looks like a slice list, so any subscription can be
576interpreted as a slicing. Rather than further complicating the syntax, this is
577disambiguated by defining that in this case the interpretation as a subscription
578takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000579slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000580
581.. index::
582 single: start (slice object attribute)
583 single: stop (slice object attribute)
584 single: step (slice object attribute)
585
Thomas Wouters53de1902007-09-04 09:03:59 +0000586The semantics for a slicing are as follows. The primary must evaluate to a
Georg Brandl96593ed2007-09-07 14:15:41 +0000587mapping object, and it is indexed (using the same :meth:`__getitem__` method as
588normal subscription) with a key that is constructed from the slice list, as
589follows. If the slice list contains at least one comma, the key is a tuple
590containing the conversion of the slice items; otherwise, the conversion of the
591lone slice item is the key. The conversion of a slice item that is an
592expression is that expression. The conversion of a proper slice is a slice
593object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
594:attr:`step` attributes are the values of the expressions given as lower bound,
595upper bound and stride, respectively, substituting ``None`` for missing
596expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000597
598
599.. _calls:
600
601Calls
602-----
603
604.. index:: single: call
605
606.. index:: object: callable
607
608A call calls a callable object (e.g., a function) with a possibly empty series
609of arguments:
610
611.. productionlist::
612 call: `primary` "(" [`argument_list` [","]
613 : | `expression` `genexpr_for`] ")"
614 argument_list: `positional_arguments` ["," `keyword_arguments`]
615 : ["," "*" `expression`]
616 : ["," "**" `expression`]
617 : | `keyword_arguments` ["," "*" `expression`]
618 : ["," "**" `expression`]
619 : | "*" `expression` ["," "**" `expression`]
620 : | "**" `expression`
621 positional_arguments: `expression` ("," `expression`)*
622 keyword_arguments: `keyword_item` ("," `keyword_item`)*
623 keyword_item: `identifier` "=" `expression`
624
625A trailing comma may be present after the positional and keyword arguments but
626does not affect the semantics.
627
628The primary must evaluate to a callable object (user-defined functions, built-in
629functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000630instances, and all objects having a :meth:`__call__` method are callable). All
631argument expressions are evaluated before the call is attempted. Please refer
632to section :ref:`function` for the syntax of formal parameter lists.
633
634.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000635
636If keyword arguments are present, they are first converted to positional
637arguments, as follows. First, a list of unfilled slots is created for the
638formal parameters. If there are N positional arguments, they are placed in the
639first N slots. Next, for each keyword argument, the identifier is used to
640determine the corresponding slot (if the identifier is the same as the first
641formal parameter name, the first slot is used, and so on). If the slot is
642already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
643the argument is placed in the slot, filling it (even if the expression is
644``None``, it fills the slot). When all arguments have been processed, the slots
645that are still unfilled are filled with the corresponding default value from the
646function definition. (Default values are calculated, once, when the function is
647defined; thus, a mutable object such as a list or dictionary used as default
648value will be shared by all calls that don't specify an argument value for the
649corresponding slot; this should usually be avoided.) If there are any unfilled
650slots for which no default value is specified, a :exc:`TypeError` exception is
651raised. Otherwise, the list of filled slots is used as the argument list for
652the call.
653
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000654.. note::
655
656 An implementation may provide builtin functions whose positional parameters do
657 not have names, even if they are 'named' for the purpose of documentation, and
658 which therefore cannot be supplied by keyword. In CPython, this is the case for
659 functions implemented in C that use :cfunc:`PyArg_ParseTuple` to parse their
660 arguments.
661
Georg Brandl116aa622007-08-15 14:28:22 +0000662If there are more positional arguments than there are formal parameter slots, a
663:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
664``*identifier`` is present; in this case, that formal parameter receives a tuple
665containing the excess positional arguments (or an empty tuple if there were no
666excess positional arguments).
667
668If any keyword argument does not correspond to a formal parameter name, a
669:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
670``**identifier`` is present; in this case, that formal parameter receives a
671dictionary containing the excess keyword arguments (using the keywords as keys
672and the argument values as corresponding values), or a (new) empty dictionary if
673there were no excess keyword arguments.
674
675If the syntax ``*expression`` appears in the function call, ``expression`` must
676evaluate to a sequence. Elements from this sequence are treated as if they were
Christian Heimesc3f30c42008-02-22 16:37:40 +0000677additional positional arguments; if there are positional arguments *x1*,...,*xN*
Georg Brandl116aa622007-08-15 14:28:22 +0000678, and ``expression`` evaluates to a sequence *y1*,...,*yM*, this is equivalent
679to a call with M+N positional arguments *x1*,...,*xN*,*y1*,...,*yM*.
680
681A consequence of this is that although the ``*expression`` syntax appears
682*after* any keyword arguments, it is processed *before* the keyword arguments
683(and the ``**expression`` argument, if any -- see below). So::
684
685 >>> def f(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000686 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000687 ...
688 >>> f(b=1, *(2,))
689 2 1
690 >>> f(a=1, *(2,))
691 Traceback (most recent call last):
692 File "<stdin>", line 1, in ?
693 TypeError: f() got multiple values for keyword argument 'a'
694 >>> f(1, *(2,))
695 1 2
696
697It is unusual for both keyword arguments and the ``*expression`` syntax to be
698used in the same call, so in practice this confusion does not arise.
699
700If the syntax ``**expression`` appears in the function call, ``expression`` must
701evaluate to a mapping, the contents of which are treated as additional keyword
702arguments. In the case of a keyword appearing in both ``expression`` and as an
703explicit keyword argument, a :exc:`TypeError` exception is raised.
704
705Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
706used as positional argument slots or as keyword argument names.
707
708A call always returns some value, possibly ``None``, unless it raises an
709exception. How this value is computed depends on the type of the callable
710object.
711
712If it is---
713
714a user-defined function:
715 .. index::
716 pair: function; call
717 triple: user-defined; function; call
718 object: user-defined function
719 object: function
720
721 The code block for the function is executed, passing it the argument list. The
722 first thing the code block will do is bind the formal parameters to the
723 arguments; this is described in section :ref:`function`. When the code block
724 executes a :keyword:`return` statement, this specifies the return value of the
725 function call.
726
727a built-in function or method:
728 .. index::
729 pair: function; call
730 pair: built-in function; call
731 pair: method; call
732 pair: built-in method; call
733 object: built-in method
734 object: built-in function
735 object: method
736 object: function
737
738 The result is up to the interpreter; see :ref:`built-in-funcs` for the
739 descriptions of built-in functions and methods.
740
741a class object:
742 .. index::
743 object: class
744 pair: class object; call
745
746 A new instance of that class is returned.
747
748a class instance method:
749 .. index::
750 object: class instance
751 object: instance
752 pair: class instance; call
753
754 The corresponding user-defined function is called, with an argument list that is
755 one longer than the argument list of the call: the instance becomes the first
756 argument.
757
758a class instance:
759 .. index::
760 pair: instance; call
761 single: __call__() (object method)
762
763 The class must define a :meth:`__call__` method; the effect is then the same as
764 if that method was called.
765
766
767.. _power:
768
769The power operator
770==================
771
772The power operator binds more tightly than unary operators on its left; it binds
773less tightly than unary operators on its right. The syntax is:
774
775.. productionlist::
776 power: `primary` ["**" `u_expr`]
777
778Thus, in an unparenthesized sequence of power and unary operators, the operators
779are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +0000780for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000781
782The power operator has the same semantics as the built-in :func:`pow` function,
783when called with two arguments: it yields its left argument raised to the power
784of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +0000785type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +0000786
Georg Brandl96593ed2007-09-07 14:15:41 +0000787For int operands, the result has the same type as the operands unless the second
788argument is negative; in that case, all arguments are converted to float and a
789float result is delivered. For example, ``10**2`` returns ``100``, but
790``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +0000791
792Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +0000793Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +0000794number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000795
796
797.. _unary:
798
799Unary arithmetic operations
800===========================
801
802.. index::
803 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +0000804 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000805
Christian Heimesfaf2f632008-01-06 16:59:19 +0000806All unary arithmetic (and bitwise) operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +0000807
808.. productionlist::
809 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
810
811.. index::
812 single: negation
813 single: minus
814
815The unary ``-`` (minus) operator yields the negation of its numeric argument.
816
817.. index:: single: plus
818
819The unary ``+`` (plus) operator yields its numeric argument unchanged.
820
821.. index:: single: inversion
822
Christian Heimesfaf2f632008-01-06 16:59:19 +0000823
Georg Brandl95817b32008-05-11 14:30:18 +0000824The unary ``~`` (invert) operator yields the bitwise inversion of its integer
825argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
826applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000827
828.. index:: exception: TypeError
829
830In all three cases, if the argument does not have the proper type, a
831:exc:`TypeError` exception is raised.
832
833
834.. _binary:
835
836Binary arithmetic operations
837============================
838
839.. index:: triple: binary; arithmetic; operation
840
841The binary arithmetic operations have the conventional priority levels. Note
842that some of these operations also apply to certain non-numeric types. Apart
843from the power operator, there are only two levels, one for multiplicative
844operators and one for additive operators:
845
846.. productionlist::
847 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
848 : | `m_expr` "%" `u_expr`
849 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
850
851.. index:: single: multiplication
852
853The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +0000854arguments must either both be numbers, or one argument must be an integer and
855the other must be a sequence. In the former case, the numbers are converted to a
856common type and then multiplied together. In the latter case, sequence
857repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000858
859.. index::
860 exception: ZeroDivisionError
861 single: division
862
863The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
864their arguments. The numeric arguments are first converted to a common type.
Georg Brandl96593ed2007-09-07 14:15:41 +0000865Integer division yields a float, while floor division of integers results in an
866integer; the result is that of mathematical division with the 'floor' function
867applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
868exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000869
870.. index:: single: modulo
871
872The ``%`` (modulo) operator yields the remainder from the division of the first
873argument by the second. The numeric arguments are first converted to a common
874type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
875arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
876(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
877result with the same sign as its second operand (or zero); the absolute value of
878the result is strictly smaller than the absolute value of the second operand
879[#]_.
880
Georg Brandl96593ed2007-09-07 14:15:41 +0000881The floor division and modulo operators are connected by the following
882identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
883connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
884x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000885
886In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +0000887also overloaded by string objects to perform old-style string formatting (also
888known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +0000889Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +0000890
891The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +0000892function are not defined for complex numbers. Instead, convert to a floating
893point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +0000894
895.. index:: single: addition
896
Georg Brandl96593ed2007-09-07 14:15:41 +0000897The ``+`` (addition) operator yields the sum of its arguments. The arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000898must either both be numbers or both sequences of the same type. In the former
899case, the numbers are converted to a common type and then added together. In
900the latter case, the sequences are concatenated.
901
902.. index:: single: subtraction
903
904The ``-`` (subtraction) operator yields the difference of its arguments. The
905numeric arguments are first converted to a common type.
906
907
908.. _shifting:
909
910Shifting operations
911===================
912
913.. index:: pair: shifting; operation
914
915The shifting operations have lower priority than the arithmetic operations:
916
917.. productionlist::
918 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
919
Georg Brandl96593ed2007-09-07 14:15:41 +0000920These operators accept integers as arguments. They shift the first argument to
921the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000922
923.. index:: exception: ValueError
924
925A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift
Georg Brandl96593ed2007-09-07 14:15:41 +0000926by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000927
928
929.. _bitwise:
930
Christian Heimesfaf2f632008-01-06 16:59:19 +0000931Binary bitwise operations
932=========================
Georg Brandl116aa622007-08-15 14:28:22 +0000933
Christian Heimesfaf2f632008-01-06 16:59:19 +0000934.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000935
936Each of the three bitwise operations has a different priority level:
937
938.. productionlist::
939 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
940 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
941 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
942
Christian Heimesfaf2f632008-01-06 16:59:19 +0000943.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +0000944
Georg Brandl96593ed2007-09-07 14:15:41 +0000945The ``&`` operator yields the bitwise AND of its arguments, which must be
946integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000947
948.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000949 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +0000950 pair: exclusive; or
951
952The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +0000953must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000956 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +0000957 pair: inclusive; or
958
959The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +0000960must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000961
962
963.. _comparisons:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000964.. _is:
965.. _isnot:
966.. _in:
967.. _notin:
Georg Brandl116aa622007-08-15 14:28:22 +0000968
969Comparisons
970===========
971
972.. index:: single: comparison
973
974.. index:: pair: C; language
975
976Unlike C, all comparison operations in Python have the same priority, which is
977lower than that of any arithmetic, shifting or bitwise operation. Also unlike
978C, expressions like ``a < b < c`` have the interpretation that is conventional
979in mathematics:
980
981.. productionlist::
982 comparison: `or_expr` ( `comp_operator` `or_expr` )*
983 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
984 : | "is" ["not"] | ["not"] "in"
985
986Comparisons yield boolean values: ``True`` or ``False``.
987
988.. index:: pair: chaining; comparisons
989
990Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
991``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
992cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
993
Guido van Rossum04110fb2007-08-24 16:32:05 +0000994Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
995*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
996to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
997evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +0000998
Guido van Rossum04110fb2007-08-24 16:32:05 +0000999Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001000*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1001pretty).
1002
1003The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1004values of two objects. The objects need not have the same type. If both are
1005numbers, they are converted to a common type. Otherwise, objects of different
1006types *always* compare unequal, and are ordered consistently but arbitrarily.
1007You can control comparison behavior of objects of non-builtin types by defining
Georg Brandl96593ed2007-09-07 14:15:41 +00001008a :meth:`__cmp__` method or rich comparison methods like :meth:`__gt__`,
1009described in section :ref:`specialnames`.
Georg Brandl116aa622007-08-15 14:28:22 +00001010
1011(This unusual definition of comparison was used to simplify the definition of
1012operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
1013In the future, the comparison rules for objects of different types are likely to
1014change.)
1015
1016Comparison of objects of the same type depends on the type:
1017
1018* Numbers are compared arithmetically.
1019
Georg Brandl96593ed2007-09-07 14:15:41 +00001020* Bytes objects are compared lexicographically using the numeric values of their
1021 elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001022
Georg Brandl116aa622007-08-15 14:28:22 +00001023* Strings are compared lexicographically using the numeric equivalents (the
Georg Brandl96593ed2007-09-07 14:15:41 +00001024 result of the built-in function :func:`ord`) of their characters. [#]_ String
1025 and bytes object can't be compared!
Georg Brandl116aa622007-08-15 14:28:22 +00001026
1027* Tuples and lists are compared lexicographically using comparison of
1028 corresponding elements. This means that to compare equal, each element must
1029 compare equal and the two sequences must be of the same type and have the same
1030 length.
1031
1032 If not equal, the sequences are ordered the same as their first differing
1033 elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
Georg Brandl96593ed2007-09-07 14:15:41 +00001034 ``cmp(x,y)``. If the corresponding element does not exist, the shorter
1035 sequence is ordered first (for example, ``[1,2] < [1,2,3]``).
Georg Brandl116aa622007-08-15 14:28:22 +00001036
Georg Brandl96593ed2007-09-07 14:15:41 +00001037* Mappings (dictionaries) compare equal if and only if their sorted ``(key,
1038 value)`` lists compare equal. [#]_ Outcomes other than equality are resolved
Georg Brandl116aa622007-08-15 14:28:22 +00001039 consistently, but are not otherwise defined. [#]_
1040
1041* Most other objects of builtin types compare unequal unless they are the same
1042 object; the choice whether one object is considered smaller or larger than
1043 another one is made arbitrarily but consistently within one execution of a
1044 program.
1045
Georg Brandl96593ed2007-09-07 14:15:41 +00001046The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
1047s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not
1048in s`` returns the negation of ``x in s``. All built-in sequences and set types
1049support this as well as dictionary, for which :keyword:`in` tests whether a the
1050dictionary has a given key.
Georg Brandl116aa622007-08-15 14:28:22 +00001051
1052For the list and tuple types, ``x in y`` is true if and only if there exists an
1053index *i* such that ``x == y[i]`` is true.
1054
Georg Brandl4b491312007-08-31 09:22:56 +00001055For the string and bytes types, ``x in y`` is true if and only if *x* is a
1056substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1057always considered to be a substring of any other string, so ``"" in "abc"`` will
1058return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001059
Georg Brandl116aa622007-08-15 14:28:22 +00001060For user-defined classes which define the :meth:`__contains__` method, ``x in
1061y`` is true if and only if ``y.__contains__(x)`` is true.
1062
1063For user-defined classes which do not define :meth:`__contains__` and do define
1064:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1065integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001066raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001067if :keyword:`in` raised that exception).
1068
1069.. index::
1070 operator: in
1071 operator: not in
1072 pair: membership; test
1073 object: sequence
1074
1075The operator :keyword:`not in` is defined to have the inverse true value of
1076:keyword:`in`.
1077
1078.. index::
1079 operator: is
1080 operator: is not
1081 pair: identity; test
1082
1083The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1084is y`` is true if and only if *x* and *y* are the same object. ``x is not y``
1085yields the inverse truth value.
1086
1087
1088.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001089.. _and:
1090.. _or:
1091.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001092
1093Boolean operations
1094==================
1095
1096.. index::
1097 pair: Conditional; expression
1098 pair: Boolean; operation
1099
1100Boolean operations have the lowest priority of all Python operations:
1101
1102.. productionlist::
1103 expression: `conditional_expression` | `lambda_form`
Georg Brandl96593ed2007-09-07 14:15:41 +00001104 expression_nocond: `or_test` | `lambda_form_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001105 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1106 or_test: `and_test` | `or_test` "or" `and_test`
1107 and_test: `not_test` | `and_test` "and" `not_test`
1108 not_test: `comparison` | "not" `not_test`
1109
1110In the context of Boolean operations, and also when expressions are used by
1111control flow statements, the following values are interpreted as false:
1112``False``, ``None``, numeric zero of all types, and empty strings and containers
1113(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001114other values are interpreted as true. User-defined objects can customize their
1115truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001116
1117.. index:: operator: not
1118
1119The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1120otherwise.
1121
1122The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is
1123true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated
1124and its value is returned.
1125
Georg Brandl116aa622007-08-15 14:28:22 +00001126.. index:: operator: and
1127
1128The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1129returned; otherwise, *y* is evaluated and the resulting value is returned.
1130
1131.. index:: operator: or
1132
1133The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1134returned; otherwise, *y* is evaluated and the resulting value is returned.
1135
1136(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1137they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001138argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001139replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1140the desired value. Because :keyword:`not` has to invent a value anyway, it does
1141not bother to return a value of the same type as its argument, so e.g., ``not
1142'foo'`` yields ``False``, not ``''``.)
1143
1144
1145.. _lambdas:
1146
1147Lambdas
1148=======
1149
1150.. index::
1151 pair: lambda; expression
1152 pair: lambda; form
1153 pair: anonymous; function
1154
1155.. productionlist::
1156 lambda_form: "lambda" [`parameter_list`]: `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +00001157 lambda_form_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001158
1159Lambda forms (lambda expressions) have the same syntactic position as
1160expressions. They are a shorthand to create anonymous functions; the expression
1161``lambda arguments: expression`` yields a function object. The unnamed object
1162behaves like a function object defined with ::
1163
Georg Brandl96593ed2007-09-07 14:15:41 +00001164 def <lambda>(arguments):
Georg Brandl116aa622007-08-15 14:28:22 +00001165 return expression
1166
1167See section :ref:`function` for the syntax of parameter lists. Note that
1168functions created with lambda forms cannot contain statements or annotations.
1169
1170.. _lambda:
1171
1172
1173.. _exprlists:
1174
1175Expression lists
1176================
1177
1178.. index:: pair: expression; list
1179
1180.. productionlist::
1181 expression_list: `expression` ( "," `expression` )* [","]
1182
1183.. index:: object: tuple
1184
1185An expression list containing at least one comma yields a tuple. The length of
1186the tuple is the number of expressions in the list. The expressions are
1187evaluated from left to right.
1188
1189.. index:: pair: trailing; comma
1190
1191The trailing comma is required only to create a single tuple (a.k.a. a
1192*singleton*); it is optional in all other cases. A single expression without a
1193trailing comma doesn't create a tuple, but rather yields the value of that
1194expression. (To create an empty tuple, use an empty pair of parentheses:
1195``()``.)
1196
1197
1198.. _evalorder:
1199
1200Evaluation order
1201================
1202
1203.. index:: pair: evaluation; order
1204
Georg Brandl96593ed2007-09-07 14:15:41 +00001205Python evaluates expressions from left to right. Notice that while evaluating
1206an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001207
1208In the following lines, expressions will be evaluated in the arithmetic order of
1209their suffixes::
1210
1211 expr1, expr2, expr3, expr4
1212 (expr1, expr2, expr3, expr4)
1213 {expr1: expr2, expr3: expr4}
1214 expr1 + expr2 * (expr3 - expr4)
1215 func(expr1, expr2, *expr3, **expr4)
1216 expr3, expr4 = expr1, expr2
1217
1218
1219.. _operator-summary:
1220
1221Summary
1222=======
1223
1224.. index:: pair: operator; precedence
1225
1226The following table summarizes the operator precedences in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001227precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001228the same box have the same precedence. Unless the syntax is explicitly given,
1229operators are binary. Operators in the same box group left to right (except for
1230comparisons, including tests, which all have the same precedence and chain from
1231left to right --- see section :ref:`comparisons` --- and exponentiation, which
1232groups from right to left).
1233
1234+----------------------------------------------+-------------------------------------+
1235| Operator | Description |
1236+==============================================+=====================================+
1237| :keyword:`lambda` | Lambda expression |
1238+----------------------------------------------+-------------------------------------+
1239| :keyword:`or` | Boolean OR |
1240+----------------------------------------------+-------------------------------------+
1241| :keyword:`and` | Boolean AND |
1242+----------------------------------------------+-------------------------------------+
1243| :keyword:`not` *x* | Boolean NOT |
1244+----------------------------------------------+-------------------------------------+
1245| :keyword:`in`, :keyword:`not` :keyword:`in` | Membership tests |
1246+----------------------------------------------+-------------------------------------+
1247| :keyword:`is`, :keyword:`is not` | Identity tests |
1248+----------------------------------------------+-------------------------------------+
1249| ``<``, ``<=``, ``>``, ``>=``, ``!=``, ``==`` | Comparisons |
1250+----------------------------------------------+-------------------------------------+
1251| ``|`` | Bitwise OR |
1252+----------------------------------------------+-------------------------------------+
1253| ``^`` | Bitwise XOR |
1254+----------------------------------------------+-------------------------------------+
1255| ``&`` | Bitwise AND |
1256+----------------------------------------------+-------------------------------------+
1257| ``<<``, ``>>`` | Shifts |
1258+----------------------------------------------+-------------------------------------+
1259| ``+``, ``-`` | Addition and subtraction |
1260+----------------------------------------------+-------------------------------------+
Georg Brandl96593ed2007-09-07 14:15:41 +00001261| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandl116aa622007-08-15 14:28:22 +00001262+----------------------------------------------+-------------------------------------+
1263| ``+x``, ``-x`` | Positive, negative |
1264+----------------------------------------------+-------------------------------------+
1265| ``~x`` | Bitwise not |
1266+----------------------------------------------+-------------------------------------+
1267| ``**`` | Exponentiation |
1268+----------------------------------------------+-------------------------------------+
1269| ``x.attribute`` | Attribute reference |
1270+----------------------------------------------+-------------------------------------+
1271| ``x[index]`` | Subscription |
1272+----------------------------------------------+-------------------------------------+
1273| ``x[index:index]`` | Slicing |
1274+----------------------------------------------+-------------------------------------+
1275| ``f(arguments...)`` | Function call |
1276+----------------------------------------------+-------------------------------------+
Georg Brandl96593ed2007-09-07 14:15:41 +00001277| ``(expressions...)`` | Binding, tuple display, generator |
1278| | expressions |
Georg Brandl116aa622007-08-15 14:28:22 +00001279+----------------------------------------------+-------------------------------------+
1280| ``[expressions...]`` | List display |
1281+----------------------------------------------+-------------------------------------+
Georg Brandl96593ed2007-09-07 14:15:41 +00001282| ``{expressions...}`` | Dictionary or set display |
Georg Brandl116aa622007-08-15 14:28:22 +00001283+----------------------------------------------+-------------------------------------+
1284
1285.. rubric:: Footnotes
1286
Georg Brandl116aa622007-08-15 14:28:22 +00001287.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1288 true numerically due to roundoff. For example, and assuming a platform on which
1289 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1290 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1291 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod`
1292 in the :mod:`math` module returns a result whose sign matches the sign of the
1293 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1294 is more appropriate depends on the application.
1295
1296.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001297 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001298 cases, Python returns the latter result, in order to preserve that
1299 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1300
Georg Brandl96593ed2007-09-07 14:15:41 +00001301.. [#] While comparisons between strings make sense at the byte level, they may
1302 be counter-intuitive to users. For example, the strings ``"\u00C7"`` and
1303 ``"\u0327\u0043"`` compare differently, even though they both represent the
Georg Brandl9afde1c2007-11-01 20:32:30 +00001304 same unicode character (LATIN CAPTITAL LETTER C WITH CEDILLA). To compare
1305 strings in a human recognizable way, compare using
1306 :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001307
Georg Brandl96593ed2007-09-07 14:15:41 +00001308.. [#] The implementation computes this efficiently, without constructing lists
1309 or sorting.
Georg Brandl116aa622007-08-15 14:28:22 +00001310
1311.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
Georg Brandl96593ed2007-09-07 14:15:41 +00001312 value) lists, but this was very expensive for the common case of comparing
1313 for equality. An even earlier version of Python compared dictionaries by
1314 identity only, but this caused surprises because people expected to be able
1315 to test a dictionary for emptiness by comparing it to ``{}``.
Georg Brandl116aa622007-08-15 14:28:22 +00001316