blob: ac3c90f0944d762f57ba955776f6e48378bbcdd8 [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
654If there are more positional arguments than there are formal parameter slots, a
655:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
656``*identifier`` is present; in this case, that formal parameter receives a tuple
657containing the excess positional arguments (or an empty tuple if there were no
658excess positional arguments).
659
660If any keyword argument does not correspond to a formal parameter name, a
661:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
662``**identifier`` is present; in this case, that formal parameter receives a
663dictionary containing the excess keyword arguments (using the keywords as keys
664and the argument values as corresponding values), or a (new) empty dictionary if
665there were no excess keyword arguments.
666
667If the syntax ``*expression`` appears in the function call, ``expression`` must
668evaluate to a sequence. Elements from this sequence are treated as if they were
Christian Heimesc3f30c42008-02-22 16:37:40 +0000669additional positional arguments; if there are positional arguments *x1*,...,*xN*
Georg Brandl116aa622007-08-15 14:28:22 +0000670, and ``expression`` evaluates to a sequence *y1*,...,*yM*, this is equivalent
671to a call with M+N positional arguments *x1*,...,*xN*,*y1*,...,*yM*.
672
673A consequence of this is that although the ``*expression`` syntax appears
674*after* any keyword arguments, it is processed *before* the keyword arguments
675(and the ``**expression`` argument, if any -- see below). So::
676
677 >>> def f(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000678 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000679 ...
680 >>> f(b=1, *(2,))
681 2 1
682 >>> f(a=1, *(2,))
683 Traceback (most recent call last):
684 File "<stdin>", line 1, in ?
685 TypeError: f() got multiple values for keyword argument 'a'
686 >>> f(1, *(2,))
687 1 2
688
689It is unusual for both keyword arguments and the ``*expression`` syntax to be
690used in the same call, so in practice this confusion does not arise.
691
692If the syntax ``**expression`` appears in the function call, ``expression`` must
693evaluate to a mapping, the contents of which are treated as additional keyword
694arguments. In the case of a keyword appearing in both ``expression`` and as an
695explicit keyword argument, a :exc:`TypeError` exception is raised.
696
697Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
698used as positional argument slots or as keyword argument names.
699
700A call always returns some value, possibly ``None``, unless it raises an
701exception. How this value is computed depends on the type of the callable
702object.
703
704If it is---
705
706a user-defined function:
707 .. index::
708 pair: function; call
709 triple: user-defined; function; call
710 object: user-defined function
711 object: function
712
713 The code block for the function is executed, passing it the argument list. The
714 first thing the code block will do is bind the formal parameters to the
715 arguments; this is described in section :ref:`function`. When the code block
716 executes a :keyword:`return` statement, this specifies the return value of the
717 function call.
718
719a built-in function or method:
720 .. index::
721 pair: function; call
722 pair: built-in function; call
723 pair: method; call
724 pair: built-in method; call
725 object: built-in method
726 object: built-in function
727 object: method
728 object: function
729
730 The result is up to the interpreter; see :ref:`built-in-funcs` for the
731 descriptions of built-in functions and methods.
732
733a class object:
734 .. index::
735 object: class
736 pair: class object; call
737
738 A new instance of that class is returned.
739
740a class instance method:
741 .. index::
742 object: class instance
743 object: instance
744 pair: class instance; call
745
746 The corresponding user-defined function is called, with an argument list that is
747 one longer than the argument list of the call: the instance becomes the first
748 argument.
749
750a class instance:
751 .. index::
752 pair: instance; call
753 single: __call__() (object method)
754
755 The class must define a :meth:`__call__` method; the effect is then the same as
756 if that method was called.
757
758
759.. _power:
760
761The power operator
762==================
763
764The power operator binds more tightly than unary operators on its left; it binds
765less tightly than unary operators on its right. The syntax is:
766
767.. productionlist::
768 power: `primary` ["**" `u_expr`]
769
770Thus, in an unparenthesized sequence of power and unary operators, the operators
771are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +0000772for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774The power operator has the same semantics as the built-in :func:`pow` function,
775when called with two arguments: it yields its left argument raised to the power
776of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +0000777type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +0000778
Georg Brandl96593ed2007-09-07 14:15:41 +0000779For int operands, the result has the same type as the operands unless the second
780argument is negative; in that case, all arguments are converted to float and a
781float result is delivered. For example, ``10**2`` returns ``100``, but
782``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +0000783
784Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +0000785Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +0000786number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000787
788
789.. _unary:
790
791Unary arithmetic operations
792===========================
793
794.. index::
795 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +0000796 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000797
Christian Heimesfaf2f632008-01-06 16:59:19 +0000798All unary arithmetic (and bitwise) operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +0000799
800.. productionlist::
801 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
802
803.. index::
804 single: negation
805 single: minus
806
807The unary ``-`` (minus) operator yields the negation of its numeric argument.
808
809.. index:: single: plus
810
811The unary ``+`` (plus) operator yields its numeric argument unchanged.
812
813.. index:: single: inversion
814
Christian Heimesfaf2f632008-01-06 16:59:19 +0000815
816The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
817long integer argument. The bitwise inversion of ``x`` is defined as
818``-(x+1)``. It only applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000819
820.. index:: exception: TypeError
821
822In all three cases, if the argument does not have the proper type, a
823:exc:`TypeError` exception is raised.
824
825
826.. _binary:
827
828Binary arithmetic operations
829============================
830
831.. index:: triple: binary; arithmetic; operation
832
833The binary arithmetic operations have the conventional priority levels. Note
834that some of these operations also apply to certain non-numeric types. Apart
835from the power operator, there are only two levels, one for multiplicative
836operators and one for additive operators:
837
838.. productionlist::
839 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
840 : | `m_expr` "%" `u_expr`
841 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
842
843.. index:: single: multiplication
844
845The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +0000846arguments must either both be numbers, or one argument must be an integer and
847the other must be a sequence. In the former case, the numbers are converted to a
848common type and then multiplied together. In the latter case, sequence
849repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851.. index::
852 exception: ZeroDivisionError
853 single: division
854
855The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
856their arguments. The numeric arguments are first converted to a common type.
Georg Brandl96593ed2007-09-07 14:15:41 +0000857Integer division yields a float, while floor division of integers results in an
858integer; the result is that of mathematical division with the 'floor' function
859applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
860exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000861
862.. index:: single: modulo
863
864The ``%`` (modulo) operator yields the remainder from the division of the first
865argument by the second. The numeric arguments are first converted to a common
866type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
867arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
868(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
869result with the same sign as its second operand (or zero); the absolute value of
870the result is strictly smaller than the absolute value of the second operand
871[#]_.
872
Georg Brandl96593ed2007-09-07 14:15:41 +0000873The floor division and modulo operators are connected by the following
874identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
875connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
876x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000877
878In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +0000879also overloaded by string objects to perform old-style string formatting (also
880known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +0000881Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +0000882
883The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +0000884function are not defined for complex numbers. Instead, convert to a floating
885point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +0000886
887.. index:: single: addition
888
Georg Brandl96593ed2007-09-07 14:15:41 +0000889The ``+`` (addition) operator yields the sum of its arguments. The arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000890must either both be numbers or both sequences of the same type. In the former
891case, the numbers are converted to a common type and then added together. In
892the latter case, the sequences are concatenated.
893
894.. index:: single: subtraction
895
896The ``-`` (subtraction) operator yields the difference of its arguments. The
897numeric arguments are first converted to a common type.
898
899
900.. _shifting:
901
902Shifting operations
903===================
904
905.. index:: pair: shifting; operation
906
907The shifting operations have lower priority than the arithmetic operations:
908
909.. productionlist::
910 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
911
Georg Brandl96593ed2007-09-07 14:15:41 +0000912These operators accept integers as arguments. They shift the first argument to
913the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000914
915.. index:: exception: ValueError
916
917A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift
Georg Brandl96593ed2007-09-07 14:15:41 +0000918by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000919
920
921.. _bitwise:
922
Christian Heimesfaf2f632008-01-06 16:59:19 +0000923Binary bitwise operations
924=========================
Georg Brandl116aa622007-08-15 14:28:22 +0000925
Christian Heimesfaf2f632008-01-06 16:59:19 +0000926.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000927
928Each of the three bitwise operations has a different priority level:
929
930.. productionlist::
931 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
932 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
933 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
934
Christian Heimesfaf2f632008-01-06 16:59:19 +0000935.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +0000936
Georg Brandl96593ed2007-09-07 14:15:41 +0000937The ``&`` operator yields the bitwise AND of its arguments, which must be
938integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000939
940.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000941 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +0000942 pair: exclusive; or
943
944The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +0000945must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000946
947.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000948 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +0000949 pair: inclusive; or
950
951The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +0000952must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000953
954
955.. _comparisons:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000956.. _is:
957.. _isnot:
958.. _in:
959.. _notin:
Georg Brandl116aa622007-08-15 14:28:22 +0000960
961Comparisons
962===========
963
964.. index:: single: comparison
965
966.. index:: pair: C; language
967
968Unlike C, all comparison operations in Python have the same priority, which is
969lower than that of any arithmetic, shifting or bitwise operation. Also unlike
970C, expressions like ``a < b < c`` have the interpretation that is conventional
971in mathematics:
972
973.. productionlist::
974 comparison: `or_expr` ( `comp_operator` `or_expr` )*
975 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
976 : | "is" ["not"] | ["not"] "in"
977
978Comparisons yield boolean values: ``True`` or ``False``.
979
980.. index:: pair: chaining; comparisons
981
982Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
983``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
984cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
985
Guido van Rossum04110fb2007-08-24 16:32:05 +0000986Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
987*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
988to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
989evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +0000990
Guido van Rossum04110fb2007-08-24 16:32:05 +0000991Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +0000992*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
993pretty).
994
995The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
996values of two objects. The objects need not have the same type. If both are
997numbers, they are converted to a common type. Otherwise, objects of different
998types *always* compare unequal, and are ordered consistently but arbitrarily.
999You can control comparison behavior of objects of non-builtin types by defining
Georg Brandl96593ed2007-09-07 14:15:41 +00001000a :meth:`__cmp__` method or rich comparison methods like :meth:`__gt__`,
1001described in section :ref:`specialnames`.
Georg Brandl116aa622007-08-15 14:28:22 +00001002
1003(This unusual definition of comparison was used to simplify the definition of
1004operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
1005In the future, the comparison rules for objects of different types are likely to
1006change.)
1007
1008Comparison of objects of the same type depends on the type:
1009
1010* Numbers are compared arithmetically.
1011
Georg Brandl96593ed2007-09-07 14:15:41 +00001012* Bytes objects are compared lexicographically using the numeric values of their
1013 elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001014
Georg Brandl116aa622007-08-15 14:28:22 +00001015* Strings are compared lexicographically using the numeric equivalents (the
Georg Brandl96593ed2007-09-07 14:15:41 +00001016 result of the built-in function :func:`ord`) of their characters. [#]_ String
1017 and bytes object can't be compared!
Georg Brandl116aa622007-08-15 14:28:22 +00001018
1019* Tuples and lists are compared lexicographically using comparison of
1020 corresponding elements. This means that to compare equal, each element must
1021 compare equal and the two sequences must be of the same type and have the same
1022 length.
1023
1024 If not equal, the sequences are ordered the same as their first differing
1025 elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
Georg Brandl96593ed2007-09-07 14:15:41 +00001026 ``cmp(x,y)``. If the corresponding element does not exist, the shorter
1027 sequence is ordered first (for example, ``[1,2] < [1,2,3]``).
Georg Brandl116aa622007-08-15 14:28:22 +00001028
Georg Brandl96593ed2007-09-07 14:15:41 +00001029* Mappings (dictionaries) compare equal if and only if their sorted ``(key,
1030 value)`` lists compare equal. [#]_ Outcomes other than equality are resolved
Georg Brandl116aa622007-08-15 14:28:22 +00001031 consistently, but are not otherwise defined. [#]_
1032
1033* Most other objects of builtin types compare unequal unless they are the same
1034 object; the choice whether one object is considered smaller or larger than
1035 another one is made arbitrarily but consistently within one execution of a
1036 program.
1037
Georg Brandl96593ed2007-09-07 14:15:41 +00001038The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
1039s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not
1040in s`` returns the negation of ``x in s``. All built-in sequences and set types
1041support this as well as dictionary, for which :keyword:`in` tests whether a the
1042dictionary has a given key.
Georg Brandl116aa622007-08-15 14:28:22 +00001043
1044For the list and tuple types, ``x in y`` is true if and only if there exists an
1045index *i* such that ``x == y[i]`` is true.
1046
Georg Brandl4b491312007-08-31 09:22:56 +00001047For the string and bytes types, ``x in y`` is true if and only if *x* is a
1048substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1049always considered to be a substring of any other string, so ``"" in "abc"`` will
1050return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001051
Georg Brandl116aa622007-08-15 14:28:22 +00001052For user-defined classes which define the :meth:`__contains__` method, ``x in
1053y`` is true if and only if ``y.__contains__(x)`` is true.
1054
1055For user-defined classes which do not define :meth:`__contains__` and do define
1056:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1057integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001058raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001059if :keyword:`in` raised that exception).
1060
1061.. index::
1062 operator: in
1063 operator: not in
1064 pair: membership; test
1065 object: sequence
1066
1067The operator :keyword:`not in` is defined to have the inverse true value of
1068:keyword:`in`.
1069
1070.. index::
1071 operator: is
1072 operator: is not
1073 pair: identity; test
1074
1075The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1076is y`` is true if and only if *x* and *y* are the same object. ``x is not y``
1077yields the inverse truth value.
1078
1079
1080.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001081.. _and:
1082.. _or:
1083.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001084
1085Boolean operations
1086==================
1087
1088.. index::
1089 pair: Conditional; expression
1090 pair: Boolean; operation
1091
1092Boolean operations have the lowest priority of all Python operations:
1093
1094.. productionlist::
1095 expression: `conditional_expression` | `lambda_form`
Georg Brandl96593ed2007-09-07 14:15:41 +00001096 expression_nocond: `or_test` | `lambda_form_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001097 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1098 or_test: `and_test` | `or_test` "or" `and_test`
1099 and_test: `not_test` | `and_test` "and" `not_test`
1100 not_test: `comparison` | "not" `not_test`
1101
1102In the context of Boolean operations, and also when expressions are used by
1103control flow statements, the following values are interpreted as false:
1104``False``, ``None``, numeric zero of all types, and empty strings and containers
1105(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001106other values are interpreted as true. User-defined objects can customize their
1107truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001108
1109.. index:: operator: not
1110
1111The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1112otherwise.
1113
1114The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is
1115true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated
1116and its value is returned.
1117
Georg Brandl116aa622007-08-15 14:28:22 +00001118.. index:: operator: and
1119
1120The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1121returned; otherwise, *y* is evaluated and the resulting value is returned.
1122
1123.. index:: operator: or
1124
1125The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1126returned; otherwise, *y* is evaluated and the resulting value is returned.
1127
1128(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1129they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001130argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001131replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1132the desired value. Because :keyword:`not` has to invent a value anyway, it does
1133not bother to return a value of the same type as its argument, so e.g., ``not
1134'foo'`` yields ``False``, not ``''``.)
1135
1136
1137.. _lambdas:
1138
1139Lambdas
1140=======
1141
1142.. index::
1143 pair: lambda; expression
1144 pair: lambda; form
1145 pair: anonymous; function
1146
1147.. productionlist::
1148 lambda_form: "lambda" [`parameter_list`]: `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +00001149 lambda_form_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001150
1151Lambda forms (lambda expressions) have the same syntactic position as
1152expressions. They are a shorthand to create anonymous functions; the expression
1153``lambda arguments: expression`` yields a function object. The unnamed object
1154behaves like a function object defined with ::
1155
Georg Brandl96593ed2007-09-07 14:15:41 +00001156 def <lambda>(arguments):
Georg Brandl116aa622007-08-15 14:28:22 +00001157 return expression
1158
1159See section :ref:`function` for the syntax of parameter lists. Note that
1160functions created with lambda forms cannot contain statements or annotations.
1161
1162.. _lambda:
1163
1164
1165.. _exprlists:
1166
1167Expression lists
1168================
1169
1170.. index:: pair: expression; list
1171
1172.. productionlist::
1173 expression_list: `expression` ( "," `expression` )* [","]
1174
1175.. index:: object: tuple
1176
1177An expression list containing at least one comma yields a tuple. The length of
1178the tuple is the number of expressions in the list. The expressions are
1179evaluated from left to right.
1180
1181.. index:: pair: trailing; comma
1182
1183The trailing comma is required only to create a single tuple (a.k.a. a
1184*singleton*); it is optional in all other cases. A single expression without a
1185trailing comma doesn't create a tuple, but rather yields the value of that
1186expression. (To create an empty tuple, use an empty pair of parentheses:
1187``()``.)
1188
1189
1190.. _evalorder:
1191
1192Evaluation order
1193================
1194
1195.. index:: pair: evaluation; order
1196
Georg Brandl96593ed2007-09-07 14:15:41 +00001197Python evaluates expressions from left to right. Notice that while evaluating
1198an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001199
1200In the following lines, expressions will be evaluated in the arithmetic order of
1201their suffixes::
1202
1203 expr1, expr2, expr3, expr4
1204 (expr1, expr2, expr3, expr4)
1205 {expr1: expr2, expr3: expr4}
1206 expr1 + expr2 * (expr3 - expr4)
1207 func(expr1, expr2, *expr3, **expr4)
1208 expr3, expr4 = expr1, expr2
1209
1210
1211.. _operator-summary:
1212
1213Summary
1214=======
1215
1216.. index:: pair: operator; precedence
1217
1218The following table summarizes the operator precedences in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001219precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001220the same box have the same precedence. Unless the syntax is explicitly given,
1221operators are binary. Operators in the same box group left to right (except for
1222comparisons, including tests, which all have the same precedence and chain from
1223left to right --- see section :ref:`comparisons` --- and exponentiation, which
1224groups from right to left).
1225
1226+----------------------------------------------+-------------------------------------+
1227| Operator | Description |
1228+==============================================+=====================================+
1229| :keyword:`lambda` | Lambda expression |
1230+----------------------------------------------+-------------------------------------+
1231| :keyword:`or` | Boolean OR |
1232+----------------------------------------------+-------------------------------------+
1233| :keyword:`and` | Boolean AND |
1234+----------------------------------------------+-------------------------------------+
1235| :keyword:`not` *x* | Boolean NOT |
1236+----------------------------------------------+-------------------------------------+
1237| :keyword:`in`, :keyword:`not` :keyword:`in` | Membership tests |
1238+----------------------------------------------+-------------------------------------+
1239| :keyword:`is`, :keyword:`is not` | Identity tests |
1240+----------------------------------------------+-------------------------------------+
1241| ``<``, ``<=``, ``>``, ``>=``, ``!=``, ``==`` | Comparisons |
1242+----------------------------------------------+-------------------------------------+
1243| ``|`` | Bitwise OR |
1244+----------------------------------------------+-------------------------------------+
1245| ``^`` | Bitwise XOR |
1246+----------------------------------------------+-------------------------------------+
1247| ``&`` | Bitwise AND |
1248+----------------------------------------------+-------------------------------------+
1249| ``<<``, ``>>`` | Shifts |
1250+----------------------------------------------+-------------------------------------+
1251| ``+``, ``-`` | Addition and subtraction |
1252+----------------------------------------------+-------------------------------------+
Georg Brandl96593ed2007-09-07 14:15:41 +00001253| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandl116aa622007-08-15 14:28:22 +00001254+----------------------------------------------+-------------------------------------+
1255| ``+x``, ``-x`` | Positive, negative |
1256+----------------------------------------------+-------------------------------------+
1257| ``~x`` | Bitwise not |
1258+----------------------------------------------+-------------------------------------+
1259| ``**`` | Exponentiation |
1260+----------------------------------------------+-------------------------------------+
1261| ``x.attribute`` | Attribute reference |
1262+----------------------------------------------+-------------------------------------+
1263| ``x[index]`` | Subscription |
1264+----------------------------------------------+-------------------------------------+
1265| ``x[index:index]`` | Slicing |
1266+----------------------------------------------+-------------------------------------+
1267| ``f(arguments...)`` | Function call |
1268+----------------------------------------------+-------------------------------------+
Georg Brandl96593ed2007-09-07 14:15:41 +00001269| ``(expressions...)`` | Binding, tuple display, generator |
1270| | expressions |
Georg Brandl116aa622007-08-15 14:28:22 +00001271+----------------------------------------------+-------------------------------------+
1272| ``[expressions...]`` | List display |
1273+----------------------------------------------+-------------------------------------+
Georg Brandl96593ed2007-09-07 14:15:41 +00001274| ``{expressions...}`` | Dictionary or set display |
Georg Brandl116aa622007-08-15 14:28:22 +00001275+----------------------------------------------+-------------------------------------+
1276
1277.. rubric:: Footnotes
1278
Georg Brandl116aa622007-08-15 14:28:22 +00001279.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1280 true numerically due to roundoff. For example, and assuming a platform on which
1281 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1282 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1283 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod`
1284 in the :mod:`math` module returns a result whose sign matches the sign of the
1285 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1286 is more appropriate depends on the application.
1287
1288.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001289 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001290 cases, Python returns the latter result, in order to preserve that
1291 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1292
Georg Brandl96593ed2007-09-07 14:15:41 +00001293.. [#] While comparisons between strings make sense at the byte level, they may
1294 be counter-intuitive to users. For example, the strings ``"\u00C7"`` and
1295 ``"\u0327\u0043"`` compare differently, even though they both represent the
Georg Brandl9afde1c2007-11-01 20:32:30 +00001296 same unicode character (LATIN CAPTITAL LETTER C WITH CEDILLA). To compare
1297 strings in a human recognizable way, compare using
1298 :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001299
Georg Brandl96593ed2007-09-07 14:15:41 +00001300.. [#] The implementation computes this efficiently, without constructing lists
1301 or sorting.
Georg Brandl116aa622007-08-15 14:28:22 +00001302
1303.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
Georg Brandl96593ed2007-09-07 14:15:41 +00001304 value) lists, but this was very expensive for the common case of comparing
1305 for equality. An even earlier version of Python compared dictionaries by
1306 identity only, but this caused surprises because people expected to be able
1307 to test a dictionary for emptiness by comparing it to ``{}``.
Georg Brandl116aa622007-08-15 14:28:22 +00001308