blob: 4677fdc85bc26e5a851043bd0b4cb5239dd21f58 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2.. _expressions:
3
4***********
5Expressions
6***********
7
8.. index:: single: expression
9
10This chapter explains the meaning of the elements of expressions in Python.
11
12.. index:: single: BNF
13
14**Syntax Notes:** In this and the following chapters, extended BNF notation will
15be used to describe syntax, not lexical analysis. When (one alternative of) a
16syntax rule has the form
17
18.. productionlist:: *
19 name: `othername`
20
21.. index:: single: syntax
22
23and no semantics are given, the semantics of this form of ``name`` are the same
24as for ``othername``.
25
26
27.. _conversions:
28
29Arithmetic conversions
30======================
31
32.. index:: pair: arithmetic; conversion
33
34When a description of an arithmetic operator below uses the phrase "the numeric
35arguments are converted to a common type," the arguments are coerced using the
36coercion rules listed at :ref:`coercion-rules`. If both arguments are standard
37numeric types, the following coercions are applied:
38
39* If either argument is a complex number, the other is converted to complex;
40
41* otherwise, if either argument is a floating point number, the other is
42 converted to floating point;
43
44* otherwise, if either argument is a long integer, the other is converted to
45 long integer;
46
47* otherwise, both must be plain integers and no conversion is necessary.
48
49Some additional rules apply for certain operators (e.g., a string left argument
50to the '%' operator). Extensions can define their own coercions.
51
52
53.. _atoms:
54
55Atoms
56=====
57
58.. index:: single: atom
59
60Atoms are the most basic elements of expressions. The simplest atoms are
61identifiers or literals. Forms enclosed in reverse quotes or in parentheses,
62brackets or braces are also categorized syntactically as atoms. The syntax for
63atoms is:
64
65.. productionlist::
66 atom: `identifier` | `literal` | `enclosure`
67 enclosure: `parenth_form` | `list_display`
Alexandre Vassalottiee936a22010-01-09 23:35:54 +000068 : | `generator_expression` | `dict_display` | `set_display`
Georg Brandl8ec7f652007-08-15 14:28:01 +000069 : | `string_conversion` | `yield_atom`
70
71
72.. _atom-identifiers:
73
74Identifiers (Names)
75-------------------
76
77.. index::
78 single: name
79 single: identifier
80
81An identifier occurring as an atom is a name. See section :ref:`identifiers`
82for lexical definition and section :ref:`naming` for documentation of naming and
83binding.
84
85.. index:: exception: NameError
86
87When the name is bound to an object, evaluation of the atom yields that object.
88When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
89exception.
90
91.. index::
92 pair: name; mangling
93 pair: private; names
94
95**Private name mangling:** When an identifier that textually occurs in a class
96definition begins with two or more underscore characters and does not end in two
97or more underscores, it is considered a :dfn:`private name` of that class.
98Private names are transformed to a longer form before code is generated for
99them. The transformation inserts the class name in front of the name, with
100leading underscores removed, and a single underscore inserted in front of the
101class name. For example, the identifier ``__spam`` occurring in a class named
102``Ham`` will be transformed to ``_Ham__spam``. This transformation is
103independent of the syntactical context in which the identifier is used. If the
104transformed name is extremely long (longer than 255 characters), implementation
105defined truncation may happen. If the class name consists only of underscores,
106no transformation is done.
107
Georg Brandl8ec7f652007-08-15 14:28:01 +0000108
109
110.. _atom-literals:
111
112Literals
113--------
114
115.. index:: single: literal
116
117Python supports string literals and various numeric literals:
118
119.. productionlist::
120 literal: `stringliteral` | `integer` | `longinteger`
121 : | `floatnumber` | `imagnumber`
122
123Evaluation of a literal yields an object of the given type (string, integer,
124long integer, floating point number, complex number) with the given value. The
125value may be approximated in the case of floating point and imaginary (complex)
126literals. See section :ref:`literals` for details.
127
128.. index::
129 triple: immutable; data; type
130 pair: immutable; object
131
132All literals correspond to immutable data types, and hence the object's identity
133is less important than its value. Multiple evaluations of literals with the
134same value (either the same occurrence in the program text or a different
135occurrence) may obtain the same object or a different object with the same
136value.
137
138
139.. _parenthesized:
140
141Parenthesized forms
142-------------------
143
144.. index:: single: parenthesized form
145
146A parenthesized form is an optional expression list enclosed in parentheses:
147
148.. productionlist::
149 parenth_form: "(" [`expression_list`] ")"
150
151A parenthesized expression list yields whatever that expression list yields: if
152the list contains at least one comma, it yields a tuple; otherwise, it yields
153the single expression that makes up the expression list.
154
155.. index:: pair: empty; tuple
156
157An empty pair of parentheses yields an empty tuple object. Since tuples are
158immutable, the rules for literals apply (i.e., two occurrences of the empty
159tuple may or may not yield the same object).
160
161.. index::
162 single: comma
163 pair: tuple; display
164
165Note that tuples are not formed by the parentheses, but rather by use of the
166comma operator. The exception is the empty tuple, for which parentheses *are*
167required --- allowing unparenthesized "nothing" in expressions would cause
168ambiguities and allow common typos to pass uncaught.
169
170
171.. _lists:
172
173List displays
174-------------
175
176.. index::
177 pair: list; display
178 pair: list; comprehensions
179
180A list display is a possibly empty series of expressions enclosed in square
181brackets:
182
183.. productionlist::
184 list_display: "[" [`expression_list` | `list_comprehension`] "]"
185 list_comprehension: `expression` `list_for`
186 list_for: "for" `target_list` "in" `old_expression_list` [`list_iter`]
187 old_expression_list: `old_expression` [("," `old_expression`)+ [","]]
Georg Brandl38c72032010-03-07 21:12:28 +0000188 old_expression: `or_test` | `old_lambda_form`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000189 list_iter: `list_for` | `list_if`
190 list_if: "if" `old_expression` [`list_iter`]
191
192.. index::
193 pair: list; comprehensions
194 object: list
195 pair: empty; list
196
197A list display yields a new list object. Its contents are specified by
198providing either a list of expressions or a list comprehension. When a
199comma-separated list of expressions is supplied, its elements are evaluated from
200left to right and placed into the list object in that order. When a list
201comprehension is supplied, it consists of a single expression followed by at
202least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if`
203clauses. In this case, the elements of the new list are those that would be
204produced by considering each of the :keyword:`for` or :keyword:`if` clauses a
205block, nesting from left to right, and evaluating the expression to produce a
206list element each time the innermost block is reached [#]_.
207
208
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000209.. _comprehensions:
210
211Displays for sets and dictionaries
212----------------------------------
213
214For constructing a set or a dictionary Python provides special syntax
215called "displays", each of them in two flavors:
216
217* either the container contents are listed explicitly, or
218
219* they are computed via a set of looping and filtering instructions, called a
220 :dfn:`comprehension`.
221
222Common syntax elements for comprehensions are:
223
224.. productionlist::
225 comprehension: `expression` `comp_for`
226 comp_for: "for" `target_list` "in" `or_test` [`comp_iter`]
227 comp_iter: `comp_for` | `comp_if`
228 comp_if: "if" `expression_nocond` [`comp_iter`]
229
230The comprehension consists of a single expression followed by at least one
231:keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` clauses.
232In this case, the elements of the new container are those that would be produced
233by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
234nesting from left to right, and evaluating the expression to produce an element
235each time the innermost block is reached.
236
237Note that the comprehension is executed in a separate scope, so names assigned
238to in the target list don't "leak" in the enclosing scope.
239
240
Georg Brandl8ec7f652007-08-15 14:28:01 +0000241.. _genexpr:
242
243Generator expressions
244---------------------
245
246.. index:: pair: generator; expression
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000247 object: generator
Georg Brandl8ec7f652007-08-15 14:28:01 +0000248
249A generator expression is a compact generator notation in parentheses:
250
251.. productionlist::
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000252 generator_expression: "(" `expression` `comp_for` ")"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000253
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000254A generator expression yields a new generator object. Its syntax is the same as
255for comprehensions, except that it is enclosed in parentheses instead of
256brackets or curly braces.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000257
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000258Variables used in the generator expression are evaluated lazily when the
259:meth:`__next__` method is called for generator object (in the same fashion as
260normal generators). However, the leftmost :keyword:`for` clause is immediately
261evaluated, so that an error produced by it can be seen before any other possible
Georg Brandl8e67ef52008-03-03 21:31:50 +0000262error in the code that handles the generator expression. Subsequent
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000263:keyword:`for` clauses cannot be evaluated immediately since they may depend on
264the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y
265in bar(x))``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000266
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000267The parentheses can be omitted on calls with only one argument. See section
Georg Brandl8ec7f652007-08-15 14:28:01 +0000268:ref:`calls` for the detail.
269
Georg Brandl8ec7f652007-08-15 14:28:01 +0000270.. _dict:
271
272Dictionary displays
273-------------------
274
275.. index:: pair: dictionary; display
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000276 key, datum, key/datum pair
277 object: dictionary
Georg Brandl8ec7f652007-08-15 14:28:01 +0000278
279A dictionary display is a possibly empty series of key/datum pairs enclosed in
280curly braces:
281
282.. productionlist::
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000283 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284 key_datum_list: `key_datum` ("," `key_datum`)* [","]
285 key_datum: `expression` ":" `expression`
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000286 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000287
288A dictionary display yields a new dictionary object.
289
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000290If a comma-separated sequence of key/datum pairs is given, they are evaluated
291from left to right to define the entries of the dictionary: each key object is
292used as a key into the dictionary to store the corresponding datum. This means
293that you can specify the same key multiple times in the key/datum list, and the
294final dictionary's value for that key will be the last one given.
295
296A dict comprehension, in contrast to list and set comprehensions, needs two
297expressions separated with a colon followed by the usual "for" and "if" clauses.
298When the comprehension is run, the resulting key and value elements are inserted
299in the new dictionary in the order they are produced.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000300
301.. index:: pair: immutable; object
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000302 hashable
Georg Brandl8ec7f652007-08-15 14:28:01 +0000303
304Restrictions on the types of the key values are listed earlier in section
Georg Brandl7c3e79f2007-11-02 20:06:17 +0000305:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000306all mutable objects.) Clashes between duplicate keys are not detected; the last
307datum (textually rightmost in the display) stored for a given key value
308prevails.
309
310
Alexandre Vassalottiee936a22010-01-09 23:35:54 +0000311.. _set:
312
313Set displays
314------------
315
316.. index:: pair: set; display
317 object: set
318
319A set display is denoted by curly braces and distinguishable from dictionary
320displays by the lack of colons separating keys and values:
321
322.. productionlist::
323 set_display: "{" (`expression_list` | `comprehension`) "}"
324
325A set display yields a new mutable set object, the contents being specified by
326either a sequence of expressions or a comprehension. When a comma-separated
327list of expressions is supplied, its elements are evaluated from left to right
328and added to the set object. When a comprehension is supplied, the set is
329constructed from the elements resulting from the comprehension.
330
331An empty set cannot be constructed with ``{}``; this literal constructs an empty
332dictionary.
333
334
Georg Brandl8ec7f652007-08-15 14:28:01 +0000335.. _string-conversions:
336
337String conversions
338------------------
339
340.. index::
341 pair: string; conversion
342 pair: reverse; quotes
343 pair: backward; quotes
344 single: back-quotes
345
346A string conversion is an expression list enclosed in reverse (a.k.a. backward)
347quotes:
348
349.. productionlist::
350 string_conversion: "'" `expression_list` "'"
351
352A string conversion evaluates the contained expression list and converts the
353resulting object into a string according to rules specific to its type.
354
355If the object is a string, a number, ``None``, or a tuple, list or dictionary
356containing only objects whose type is one of these, the resulting string is a
357valid Python expression which can be passed to the built-in function
358:func:`eval` to yield an expression with the same value (or an approximation, if
359floating point numbers are involved).
360
361(In particular, converting a string adds quotes around it and converts "funny"
362characters to escape sequences that are safe to print.)
363
364.. index:: object: recursive
365
366Recursive objects (for example, lists or dictionaries that contain a reference
367to themselves, directly or indirectly) use ``...`` to indicate a recursive
368reference, and the result cannot be passed to :func:`eval` to get an equal value
369(:exc:`SyntaxError` will be raised instead).
370
371.. index::
372 builtin: repr
373 builtin: str
374
375The built-in function :func:`repr` performs exactly the same conversion in its
376argument as enclosing it in parentheses and reverse quotes does. The built-in
377function :func:`str` performs a similar but more user-friendly conversion.
378
379
380.. _yieldexpr:
381
382Yield expressions
383-----------------
384
385.. index::
386 keyword: yield
387 pair: yield; expression
388 pair: generator; function
389
390.. productionlist::
391 yield_atom: "(" `yield_expression` ")"
392 yield_expression: "yield" [`expression_list`]
393
394.. versionadded:: 2.5
395
396The :keyword:`yield` expression is only used when defining a generator function,
397and can only be used in the body of a function definition. Using a
398:keyword:`yield` expression in a function definition is sufficient to cause that
399definition to create a generator function instead of a normal function.
400
401When a generator function is called, it returns an iterator known as a
402generator. That generator then controls the execution of a generator function.
403The execution starts when one of the generator's methods is called. At that
404time, the execution proceeds to the first :keyword:`yield` expression, where it
405is suspended again, returning the value of :token:`expression_list` to
406generator's caller. By suspended we mean that all local state is retained,
407including the current bindings of local variables, the instruction pointer, and
408the internal evaluation stack. When the execution is resumed by calling one of
409the generator's methods, the function can proceed exactly as if the
410:keyword:`yield` expression was just another external call. The value of the
411:keyword:`yield` expression after resuming depends on the method which resumed
412the execution.
413
414.. index:: single: coroutine
415
416All of this makes generator functions quite similar to coroutines; they yield
417multiple times, they have more than one entry point and their execution can be
418suspended. The only difference is that a generator function cannot control
419where should the execution continue after it yields; the control is always
420transfered to the generator's caller.
421
422.. index:: object: generator
423
424The following generator's methods can be used to control the execution of a
425generator function:
426
427.. index:: exception: StopIteration
428
429
430.. method:: generator.next()
431
432 Starts the execution of a generator function or resumes it at the last executed
433 :keyword:`yield` expression. When a generator function is resumed with a
434 :meth:`next` method, the current :keyword:`yield` expression always evaluates to
435 :const:`None`. The execution then continues to the next :keyword:`yield`
436 expression, where the generator is suspended again, and the value of the
437 :token:`expression_list` is returned to :meth:`next`'s caller. If the generator
438 exits without yielding another value, a :exc:`StopIteration` exception is
439 raised.
440
441
442.. method:: generator.send(value)
443
444 Resumes the execution and "sends" a value into the generator function. The
445 ``value`` argument becomes the result of the current :keyword:`yield`
446 expression. The :meth:`send` method returns the next value yielded by the
447 generator, or raises :exc:`StopIteration` if the generator exits without
448 yielding another value. When :meth:`send` is called to start the generator, it
449 must be called with :const:`None` as the argument, because there is no
Georg Brandl907a7202008-02-22 12:31:45 +0000450 :keyword:`yield` expression that could receive the value.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000451
452
453.. method:: generator.throw(type[, value[, traceback]])
454
455 Raises an exception of type ``type`` at the point where generator was paused,
456 and returns the next value yielded by the generator function. If the generator
457 exits without yielding another value, a :exc:`StopIteration` exception is
458 raised. If the generator function does not catch the passed-in exception, or
459 raises a different exception, then that exception propagates to the caller.
460
461.. index:: exception: GeneratorExit
462
463
464.. method:: generator.close()
465
466 Raises a :exc:`GeneratorExit` at the point where the generator function was
467 paused. If the generator function then raises :exc:`StopIteration` (by exiting
468 normally, or due to already being closed) or :exc:`GeneratorExit` (by not
469 catching the exception), close returns to its caller. If the generator yields a
470 value, a :exc:`RuntimeError` is raised. If the generator raises any other
471 exception, it is propagated to the caller. :meth:`close` does nothing if the
472 generator has already exited due to an exception or normal exit.
473
474Here is a simple example that demonstrates the behavior of generators and
475generator functions::
476
477 >>> def echo(value=None):
478 ... print "Execution starts when 'next()' is called for the first time."
479 ... try:
480 ... while True:
481 ... try:
482 ... value = (yield value)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000483 ... except Exception, e:
484 ... value = e
485 ... finally:
486 ... print "Don't forget to clean up when 'close()' is called."
487 ...
488 >>> generator = echo(1)
489 >>> print generator.next()
490 Execution starts when 'next()' is called for the first time.
491 1
492 >>> print generator.next()
493 None
494 >>> print generator.send(2)
495 2
496 >>> generator.throw(TypeError, "spam")
497 TypeError('spam',)
498 >>> generator.close()
499 Don't forget to clean up when 'close()' is called.
500
501
502.. seealso::
503
504 :pep:`0342` - Coroutines via Enhanced Generators
505 The proposal to enhance the API and syntax of generators, making them usable as
506 simple coroutines.
507
508
509.. _primaries:
510
511Primaries
512=========
513
514.. index:: single: primary
515
516Primaries represent the most tightly bound operations of the language. Their
517syntax is:
518
519.. productionlist::
520 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
521
522
523.. _attribute-references:
524
525Attribute references
526--------------------
527
528.. index:: pair: attribute; reference
529
530An attribute reference is a primary followed by a period and a name:
531
532.. productionlist::
533 attributeref: `primary` "." `identifier`
534
535.. index::
536 exception: AttributeError
537 object: module
538 object: list
539
540The primary must evaluate to an object of a type that supports attribute
541references, e.g., a module, list, or an instance. This object is then asked to
542produce the attribute whose name is the identifier. If this attribute is not
543available, the exception :exc:`AttributeError` is raised. Otherwise, the type
544and value of the object produced is determined by the object. Multiple
545evaluations of the same attribute reference may yield different objects.
546
547
548.. _subscriptions:
549
550Subscriptions
551-------------
552
553.. index:: single: subscription
554
555.. index::
556 object: sequence
557 object: mapping
558 object: string
559 object: tuple
560 object: list
561 object: dictionary
562 pair: sequence; item
563
564A subscription selects an item of a sequence (string, tuple or list) or mapping
565(dictionary) object:
566
567.. productionlist::
568 subscription: `primary` "[" `expression_list` "]"
569
570The primary must evaluate to an object of a sequence or mapping type.
571
572If the primary is a mapping, the expression list must evaluate to an object
573whose value is one of the keys of the mapping, and the subscription selects the
574value in the mapping that corresponds to that key. (The expression list is a
575tuple except if it has exactly one item.)
576
577If the primary is a sequence, the expression (list) must evaluate to a plain
578integer. If this value is negative, the length of the sequence is added to it
579(so that, e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value
580must be a nonnegative integer less than the number of items in the sequence, and
581the subscription selects the item whose index is that value (counting from
582zero).
583
584.. index::
585 single: character
586 pair: string; item
587
588A string's items are characters. A character is not a separate data type but a
589string of exactly one character.
590
591
592.. _slicings:
593
594Slicings
595--------
596
597.. index::
598 single: slicing
599 single: slice
600
601.. index::
602 object: sequence
603 object: string
604 object: tuple
605 object: list
606
607A slicing selects a range of items in a sequence object (e.g., a string, tuple
608or list). Slicings may be used as expressions or as targets in assignment or
609:keyword:`del` statements. The syntax for a slicing:
610
611.. productionlist::
612 slicing: `simple_slicing` | `extended_slicing`
613 simple_slicing: `primary` "[" `short_slice` "]"
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000614 extended_slicing: `primary` "[" `slice_list` "]"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000615 slice_list: `slice_item` ("," `slice_item`)* [","]
616 slice_item: `expression` | `proper_slice` | `ellipsis`
617 proper_slice: `short_slice` | `long_slice`
618 short_slice: [`lower_bound`] ":" [`upper_bound`]
619 long_slice: `short_slice` ":" [`stride`]
620 lower_bound: `expression`
621 upper_bound: `expression`
622 stride: `expression`
623 ellipsis: "..."
624
625.. index:: pair: extended; slicing
626
627There is ambiguity in the formal syntax here: anything that looks like an
628expression list also looks like a slice list, so any subscription can be
629interpreted as a slicing. Rather than further complicating the syntax, this is
630disambiguated by defining that in this case the interpretation as a subscription
631takes priority over the interpretation as a slicing (this is the case if the
632slice list contains no proper slice nor ellipses). Similarly, when the slice
633list has exactly one short slice and no trailing comma, the interpretation as a
634simple slicing takes priority over that as an extended slicing.
635
636The semantics for a simple slicing are as follows. The primary must evaluate to
637a sequence object. The lower and upper bound expressions, if present, must
638evaluate to plain integers; defaults are zero and the ``sys.maxint``,
639respectively. If either bound is negative, the sequence's length is added to
640it. The slicing now selects all items with index *k* such that ``i <= k < j``
641where *i* and *j* are the specified lower and upper bounds. This may be an
642empty sequence. It is not an error if *i* or *j* lie outside the range of valid
643indexes (such items don't exist so they aren't selected).
644
645.. index::
646 single: start (slice object attribute)
647 single: stop (slice object attribute)
648 single: step (slice object attribute)
649
650The semantics for an extended slicing are as follows. The primary must evaluate
651to a mapping object, and it is indexed with a key that is constructed from the
652slice list, as follows. If the slice list contains at least one comma, the key
653is a tuple containing the conversion of the slice items; otherwise, the
654conversion of the lone slice item is the key. The conversion of a slice item
655that is an expression is that expression. The conversion of an ellipsis slice
656item is the built-in ``Ellipsis`` object. The conversion of a proper slice is a
657slice object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
658:attr:`step` attributes are the values of the expressions given as lower bound,
659upper bound and stride, respectively, substituting ``None`` for missing
660expressions.
661
662
663.. _calls:
664
665Calls
666-----
667
668.. index:: single: call
669
670.. index:: object: callable
671
672A call calls a callable object (e.g., a function) with a possibly empty series
673of arguments:
674
675.. productionlist::
676 call: `primary` "(" [`argument_list` [","]
677 : | `expression` `genexpr_for`] ")"
678 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000679 : ["," "*" `expression`] ["," `keyword_arguments`]
680 : ["," "**" `expression`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000681 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000682 : ["," "**" `expression`]
683 : | "*" `expression` ["," "*" `expression`] ["," "**" `expression`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000684 : | "**" `expression`
685 positional_arguments: `expression` ("," `expression`)*
686 keyword_arguments: `keyword_item` ("," `keyword_item`)*
687 keyword_item: `identifier` "=" `expression`
688
689A trailing comma may be present after the positional and keyword arguments but
690does not affect the semantics.
691
692The primary must evaluate to a callable object (user-defined functions, built-in
693functions, methods of built-in objects, class objects, methods of class
694instances, and certain class instances themselves are callable; extensions may
695define additional callable object types). All argument expressions are
696evaluated before the call is attempted. Please refer to section :ref:`function`
697for the syntax of formal parameter lists.
698
699If keyword arguments are present, they are first converted to positional
700arguments, as follows. First, a list of unfilled slots is created for the
701formal parameters. If there are N positional arguments, they are placed in the
702first N slots. Next, for each keyword argument, the identifier is used to
703determine the corresponding slot (if the identifier is the same as the first
704formal parameter name, the first slot is used, and so on). If the slot is
705already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
706the argument is placed in the slot, filling it (even if the expression is
707``None``, it fills the slot). When all arguments have been processed, the slots
708that are still unfilled are filled with the corresponding default value from the
709function definition. (Default values are calculated, once, when the function is
710defined; thus, a mutable object such as a list or dictionary used as default
711value will be shared by all calls that don't specify an argument value for the
712corresponding slot; this should usually be avoided.) If there are any unfilled
713slots for which no default value is specified, a :exc:`TypeError` exception is
714raised. Otherwise, the list of filled slots is used as the argument list for
715the call.
716
Georg Brandl6c14e582009-10-22 11:48:10 +0000717.. impl-detail::
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000718
Georg Brandl6c14e582009-10-22 11:48:10 +0000719 An implementation may provide built-in functions whose positional parameters
720 do not have names, even if they are 'named' for the purpose of documentation,
721 and which therefore cannot be supplied by keyword. In CPython, this is the
722 case for functions implemented in C that use :cfunc:`PyArg_ParseTuple` to
723 parse their arguments.
Georg Brandlf8770fb2008-04-27 09:39:59 +0000724
Georg Brandl8ec7f652007-08-15 14:28:01 +0000725If there are more positional arguments than there are formal parameter slots, a
726:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
727``*identifier`` is present; in this case, that formal parameter receives a tuple
728containing the excess positional arguments (or an empty tuple if there were no
729excess positional arguments).
730
731If any keyword argument does not correspond to a formal parameter name, a
732:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
733``**identifier`` is present; in this case, that formal parameter receives a
734dictionary containing the excess keyword arguments (using the keywords as keys
735and the argument values as corresponding values), or a (new) empty dictionary if
736there were no excess keyword arguments.
737
738If the syntax ``*expression`` appears in the function call, ``expression`` must
739evaluate to a sequence. Elements from this sequence are treated as if they were
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000740additional positional arguments; if there are positional arguments *x1*,...,
741*xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this is
742equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*, ...,
743*yM*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000744
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000745A consequence of this is that although the ``*expression`` syntax may appear
746*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl8ec7f652007-08-15 14:28:01 +0000747(and the ``**expression`` argument, if any -- see below). So::
748
749 >>> def f(a, b):
750 ... print a, b
751 ...
752 >>> f(b=1, *(2,))
753 2 1
754 >>> f(a=1, *(2,))
755 Traceback (most recent call last):
756 File "<stdin>", line 1, in ?
757 TypeError: f() got multiple values for keyword argument 'a'
758 >>> f(1, *(2,))
759 1 2
760
761It is unusual for both keyword arguments and the ``*expression`` syntax to be
762used in the same call, so in practice this confusion does not arise.
763
764If the syntax ``**expression`` appears in the function call, ``expression`` must
765evaluate to a mapping, the contents of which are treated as additional keyword
766arguments. In the case of a keyword appearing in both ``expression`` and as an
767explicit keyword argument, a :exc:`TypeError` exception is raised.
768
769Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
770used as positional argument slots or as keyword argument names. Formal
771parameters using the syntax ``(sublist)`` cannot be used as keyword argument
772names; the outermost sublist corresponds to a single unnamed argument slot, and
773the argument value is assigned to the sublist using the usual tuple assignment
774rules after all other parameter processing is done.
775
776A call always returns some value, possibly ``None``, unless it raises an
777exception. How this value is computed depends on the type of the callable
778object.
779
780If it is---
781
782a user-defined function:
783 .. index::
784 pair: function; call
785 triple: user-defined; function; call
786 object: user-defined function
787 object: function
788
789 The code block for the function is executed, passing it the argument list. The
790 first thing the code block will do is bind the formal parameters to the
791 arguments; this is described in section :ref:`function`. When the code block
792 executes a :keyword:`return` statement, this specifies the return value of the
793 function call.
794
795a built-in function or method:
796 .. index::
797 pair: function; call
798 pair: built-in function; call
799 pair: method; call
800 pair: built-in method; call
801 object: built-in method
802 object: built-in function
803 object: method
804 object: function
805
806 The result is up to the interpreter; see :ref:`built-in-funcs` for the
807 descriptions of built-in functions and methods.
808
809a class object:
810 .. index::
811 object: class
812 pair: class object; call
813
814 A new instance of that class is returned.
815
816a class instance method:
817 .. index::
818 object: class instance
819 object: instance
820 pair: class instance; call
821
822 The corresponding user-defined function is called, with an argument list that is
823 one longer than the argument list of the call: the instance becomes the first
824 argument.
825
826a class instance:
827 .. index::
828 pair: instance; call
829 single: __call__() (object method)
830
831 The class must define a :meth:`__call__` method; the effect is then the same as
832 if that method was called.
833
834
835.. _power:
836
837The power operator
838==================
839
840The power operator binds more tightly than unary operators on its left; it binds
841less tightly than unary operators on its right. The syntax is:
842
843.. productionlist::
844 power: `primary` ["**" `u_expr`]
845
846Thus, in an unparenthesized sequence of power and unary operators, the operators
847are evaluated from right to left (this does not constrain the evaluation order
Georg Brandlff457b12007-08-21 06:07:08 +0000848for the operands): ``-1**2`` results in ``-1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000849
850The power operator has the same semantics as the built-in :func:`pow` function,
851when called with two arguments: it yields its left argument raised to the power
852of its right argument. The numeric arguments are first converted to a common
853type. The result type is that of the arguments after coercion.
854
855With mixed operand types, the coercion rules for binary arithmetic operators
856apply. For int and long int operands, the result has the same type as the
857operands (after coercion) unless the second argument is negative; in that case,
858all arguments are converted to float and a float result is delivered. For
859example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last
860feature was added in Python 2.2. In Python 2.1 and before, if both arguments
861were of integer types and the second argument was negative, an exception was
862raised).
863
864Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000865Raising a negative number to a fractional power results in a :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000866
867
868.. _unary:
869
Georg Brandle7cb1ce2009-02-19 08:30:06 +0000870Unary arithmetic and bitwise operations
871=======================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000872
873.. index::
874 triple: unary; arithmetic; operation
Georg Brandlf725b952008-01-05 19:44:22 +0000875 triple: unary; bitwise; operation
Georg Brandl8ec7f652007-08-15 14:28:01 +0000876
Georg Brandle7cb1ce2009-02-19 08:30:06 +0000877All unary arithmetic and bitwise operations have the same priority:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000878
879.. productionlist::
880 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
881
882.. index::
883 single: negation
884 single: minus
885
886The unary ``-`` (minus) operator yields the negation of its numeric argument.
887
888.. index:: single: plus
889
890The unary ``+`` (plus) operator yields its numeric argument unchanged.
891
892.. index:: single: inversion
893
Georg Brandlf725b952008-01-05 19:44:22 +0000894The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
895long integer argument. The bitwise inversion of ``x`` is defined as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000896``-(x+1)``. It only applies to integral numbers.
897
898.. index:: exception: TypeError
899
900In all three cases, if the argument does not have the proper type, a
901:exc:`TypeError` exception is raised.
902
903
904.. _binary:
905
906Binary arithmetic operations
907============================
908
909.. index:: triple: binary; arithmetic; operation
910
911The binary arithmetic operations have the conventional priority levels. Note
912that some of these operations also apply to certain non-numeric types. Apart
913from the power operator, there are only two levels, one for multiplicative
914operators and one for additive operators:
915
916.. productionlist::
917 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
918 : | `m_expr` "%" `u_expr`
919 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
920
921.. index:: single: multiplication
922
923The ``*`` (multiplication) operator yields the product of its arguments. The
924arguments must either both be numbers, or one argument must be an integer (plain
925or long) and the other must be a sequence. In the former case, the numbers are
926converted to a common type and then multiplied together. In the latter case,
927sequence repetition is performed; a negative repetition factor yields an empty
928sequence.
929
930.. index::
931 exception: ZeroDivisionError
932 single: division
933
934The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
935their arguments. The numeric arguments are first converted to a common type.
936Plain or long integer division yields an integer of the same type; the result is
937that of mathematical division with the 'floor' function applied to the result.
938Division by zero raises the :exc:`ZeroDivisionError` exception.
939
940.. index:: single: modulo
941
942The ``%`` (modulo) operator yields the remainder from the division of the first
943argument by the second. The numeric arguments are first converted to a common
944type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
945arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
946(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
947result with the same sign as its second operand (or zero); the absolute value of
948the result is strictly smaller than the absolute value of the second operand
949[#]_.
950
951The integer division and modulo operators are connected by the following
952identity: ``x == (x/y)*y + (x%y)``. Integer division and modulo are also
953connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y,
954x%y)``. These identities don't hold for floating point numbers; there similar
955identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
956``floor(x/y) - 1`` [#]_.
957
958In addition to performing the modulo operation on numbers, the ``%`` operator is
959also overloaded by string and unicode objects to perform string formatting (also
960known as interpolation). The syntax for string formatting is described in the
961Python Library Reference, section :ref:`string-formatting`.
962
963.. deprecated:: 2.3
964 The floor division operator, the modulo operator, and the :func:`divmod`
965 function are no longer defined for complex numbers. Instead, convert to a
966 floating point number using the :func:`abs` function if appropriate.
967
968.. index:: single: addition
969
970The ``+`` (addition) operator yields the sum of its arguments. The arguments
971must either both be numbers or both sequences of the same type. In the former
972case, the numbers are converted to a common type and then added together. In
973the latter case, the sequences are concatenated.
974
975.. index:: single: subtraction
976
977The ``-`` (subtraction) operator yields the difference of its arguments. The
978numeric arguments are first converted to a common type.
979
980
981.. _shifting:
982
983Shifting operations
984===================
985
986.. index:: pair: shifting; operation
987
988The shifting operations have lower priority than the arithmetic operations:
989
990.. productionlist::
991 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
992
993These operators accept plain or long integers as arguments. The arguments are
994converted to a common type. They shift the first argument to the left or right
995by the number of bits given by the second argument.
996
997.. index:: exception: ValueError
998
Georg Brandle9135ba2008-05-11 10:55:59 +0000999A right shift by *n* bits is defined as division by ``pow(2, n)``. A left shift
1000by *n* bits is defined as multiplication with ``pow(2, n)``. Negative shift
1001counts raise a :exc:`ValueError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001002
1003
1004.. _bitwise:
1005
Georg Brandlf725b952008-01-05 19:44:22 +00001006Binary bitwise operations
1007=========================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001008
Georg Brandlf725b952008-01-05 19:44:22 +00001009.. index:: triple: binary; bitwise; operation
Georg Brandl8ec7f652007-08-15 14:28:01 +00001010
1011Each of the three bitwise operations has a different priority level:
1012
1013.. productionlist::
1014 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1015 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1016 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1017
Georg Brandlf725b952008-01-05 19:44:22 +00001018.. index:: pair: bitwise; and
Georg Brandl8ec7f652007-08-15 14:28:01 +00001019
1020The ``&`` operator yields the bitwise AND of its arguments, which must be plain
1021or long integers. The arguments are converted to a common type.
1022
1023.. index::
Georg Brandlf725b952008-01-05 19:44:22 +00001024 pair: bitwise; xor
Georg Brandl8ec7f652007-08-15 14:28:01 +00001025 pair: exclusive; or
1026
1027The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
1028must be plain or long integers. The arguments are converted to a common type.
1029
1030.. index::
Georg Brandlf725b952008-01-05 19:44:22 +00001031 pair: bitwise; or
Georg Brandl8ec7f652007-08-15 14:28:01 +00001032 pair: inclusive; or
1033
1034The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
1035must be plain or long integers. The arguments are converted to a common type.
1036
1037
1038.. _comparisons:
Georg Brandlb19be572007-12-29 10:57:00 +00001039.. _is:
1040.. _isnot:
1041.. _in:
1042.. _notin:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001043
1044Comparisons
1045===========
1046
1047.. index:: single: comparison
1048
1049.. index:: pair: C; language
1050
1051Unlike C, all comparison operations in Python have the same priority, which is
1052lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1053C, expressions like ``a < b < c`` have the interpretation that is conventional
1054in mathematics:
1055
1056.. productionlist::
1057 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1058 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
1059 : | "is" ["not"] | ["not"] "in"
1060
1061Comparisons yield boolean values: ``True`` or ``False``.
1062
1063.. index:: pair: chaining; comparisons
1064
1065Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1066``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1067cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1068
Georg Brandl32008322007-08-21 06:12:19 +00001069Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1070*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1071to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1072evaluated at most once.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001073
Georg Brandl32008322007-08-21 06:12:19 +00001074Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl8ec7f652007-08-15 14:28:01 +00001075*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1076pretty).
1077
1078The forms ``<>`` and ``!=`` are equivalent; for consistency with C, ``!=`` is
1079preferred; where ``!=`` is mentioned below ``<>`` is also accepted. The ``<>``
1080spelling is considered obsolescent.
1081
1082The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1083values of two objects. The objects need not have the same type. If both are
1084numbers, they are converted to a common type. Otherwise, objects of different
1085types *always* compare unequal, and are ordered consistently but arbitrarily.
Georg Brandld7d4fd72009-07-26 14:37:28 +00001086You can control comparison behavior of objects of non-built-in types by defining
Georg Brandl8ec7f652007-08-15 14:28:01 +00001087a ``__cmp__`` method or rich comparison methods like ``__gt__``, described in
1088section :ref:`specialnames`.
1089
1090(This unusual definition of comparison was used to simplify the definition of
1091operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
1092In the future, the comparison rules for objects of different types are likely to
1093change.)
1094
1095Comparison of objects of the same type depends on the type:
1096
1097* Numbers are compared arithmetically.
1098
1099* Strings are compared lexicographically using the numeric equivalents (the
1100 result of the built-in function :func:`ord`) of their characters. Unicode and
Mark Summerfield216ad332007-08-16 10:09:22 +00001101 8-bit strings are fully interoperable in this behavior. [#]_
Georg Brandl8ec7f652007-08-15 14:28:01 +00001102
1103* Tuples and lists are compared lexicographically using comparison of
1104 corresponding elements. This means that to compare equal, each element must
1105 compare equal and the two sequences must be of the same type and have the same
1106 length.
1107
1108 If not equal, the sequences are ordered the same as their first differing
1109 elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
1110 ``cmp(x,y)``. If the corresponding element does not exist, the shorter sequence
1111 is ordered first (for example, ``[1,2] < [1,2,3]``).
1112
1113* Mappings (dictionaries) compare equal if and only if their sorted (key, value)
1114 lists compare equal. [#]_ Outcomes other than equality are resolved
1115 consistently, but are not otherwise defined. [#]_
1116
Georg Brandld7d4fd72009-07-26 14:37:28 +00001117* Most other objects of built-in types compare unequal unless they are the same
Georg Brandl8ec7f652007-08-15 14:28:01 +00001118 object; the choice whether one object is considered smaller or larger than
1119 another one is made arbitrarily but consistently within one execution of a
1120 program.
1121
Georg Brandl2eee1d42009-10-22 15:00:06 +00001122.. _membership-test-details:
1123
Georg Brandl489343e2008-03-28 12:24:51 +00001124The operators :keyword:`in` and :keyword:`not in` test for collection
1125membership. ``x in s`` evaluates to true if *x* is a member of the collection
1126*s*, and false otherwise. ``x not in s`` returns the negation of ``x in s``.
1127The collection membership test has traditionally been bound to sequences; an
1128object is a member of a collection if the collection is a sequence and contains
1129an element equal to that object. However, it make sense for many other object
1130types to support membership tests without being a sequence. In particular,
1131dictionaries (for keys) and sets support membership testing.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001132
1133For the list and tuple types, ``x in y`` is true if and only if there exists an
1134index *i* such that ``x == y[i]`` is true.
1135
1136For the Unicode and string types, ``x in y`` is true if and only if *x* is a
1137substring of *y*. An equivalent test is ``y.find(x) != -1``. Note, *x* and *y*
1138need not be the same type; consequently, ``u'ab' in 'abc'`` will return
1139``True``. Empty strings are always considered to be a substring of any other
1140string, so ``"" in "abc"`` will return ``True``.
1141
1142.. versionchanged:: 2.3
1143 Previously, *x* was required to be a string of length ``1``.
1144
1145For user-defined classes which define the :meth:`__contains__` method, ``x in
1146y`` is true if and only if ``y.__contains__(x)`` is true.
1147
Georg Brandl2eee1d42009-10-22 15:00:06 +00001148For user-defined classes which do not define :meth:`__contains__` but do define
1149:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1150produced while iterating over ``y``. If an exception is raised during the
1151iteration, it is as if :keyword:`in` raised that exception.
1152
1153Lastly, the old-style iteration protocol is tried: if a class defines
Georg Brandl8ec7f652007-08-15 14:28:01 +00001154:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1155integer index *i* such that ``x == y[i]``, and all lower integer indices do not
1156raise :exc:`IndexError` exception. (If any other exception is raised, it is as
1157if :keyword:`in` raised that exception).
1158
1159.. index::
1160 operator: in
1161 operator: not in
1162 pair: membership; test
1163 object: sequence
1164
1165The operator :keyword:`not in` is defined to have the inverse true value of
1166:keyword:`in`.
1167
1168.. index::
1169 operator: is
1170 operator: is not
1171 pair: identity; test
1172
1173The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1174is y`` is true if and only if *x* and *y* are the same object. ``x is not y``
Georg Brandl3214a012008-07-01 20:50:02 +00001175yields the inverse truth value. [#]_
Georg Brandl8ec7f652007-08-15 14:28:01 +00001176
1177
1178.. _booleans:
Georg Brandlb19be572007-12-29 10:57:00 +00001179.. _and:
1180.. _or:
1181.. _not:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001182
1183Boolean operations
1184==================
1185
1186.. index::
1187 pair: Conditional; expression
1188 pair: Boolean; operation
1189
Georg Brandl8ec7f652007-08-15 14:28:01 +00001190.. productionlist::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001191 or_test: `and_test` | `or_test` "or" `and_test`
1192 and_test: `not_test` | `and_test` "and" `not_test`
1193 not_test: `comparison` | "not" `not_test`
1194
1195In the context of Boolean operations, and also when expressions are used by
1196control flow statements, the following values are interpreted as false:
1197``False``, ``None``, numeric zero of all types, and empty strings and containers
1198(including strings, tuples, lists, dictionaries, sets and frozensets). All
Benjamin Petersonfe7c26d2008-09-23 13:32:46 +00001199other values are interpreted as true. (See the :meth:`~object.__nonzero__`
1200special method for a way to change this.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001201
1202.. index:: operator: not
1203
1204The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1205otherwise.
1206
Georg Brandl8ec7f652007-08-15 14:28:01 +00001207.. index:: operator: and
1208
1209The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1210returned; otherwise, *y* is evaluated and the resulting value is returned.
1211
1212.. index:: operator: or
1213
1214The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1215returned; otherwise, *y* is evaluated and the resulting value is returned.
1216
1217(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1218they return to ``False`` and ``True``, but rather return the last evaluated
1219argument. This is sometimes useful, e.g., if ``s`` is a string that should be
1220replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1221the desired value. Because :keyword:`not` has to invent a value anyway, it does
1222not bother to return a value of the same type as its argument, so e.g., ``not
1223'foo'`` yields ``False``, not ``''``.)
1224
1225
Georg Brandl38c72032010-03-07 21:12:28 +00001226Conditional Expressions
1227=======================
1228
1229.. versionadded:: 2.5
1230
1231.. index::
1232 pair: conditional; expression
1233 pair: ternary; operator
1234
1235.. productionlist::
1236 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1237 expression: `conditional_expression` | `lambda_form`
1238
1239Conditional expressions (sometimes called a "ternary operator") have the lowest
1240priority of all Python operations.
1241
Georg Brandld22557c2010-03-08 16:28:40 +00001242The expression ``x if C else y`` first evaluates the condition, *C* (*not* *x*);
Georg Brandl38c72032010-03-07 21:12:28 +00001243if *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
1244evaluated and its value is returned.
1245
1246See :pep:`308` for more details about conditional expressions.
1247
1248
Georg Brandl8ec7f652007-08-15 14:28:01 +00001249.. _lambdas:
Georg Brandl5623e502009-04-10 08:16:47 +00001250.. _lambda:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001251
1252Lambdas
1253=======
1254
1255.. index::
1256 pair: lambda; expression
1257 pair: lambda; form
1258 pair: anonymous; function
1259
1260.. productionlist::
1261 lambda_form: "lambda" [`parameter_list`]: `expression`
1262 old_lambda_form: "lambda" [`parameter_list`]: `old_expression`
1263
1264Lambda forms (lambda expressions) have the same syntactic position as
1265expressions. They are a shorthand to create anonymous functions; the expression
1266``lambda arguments: expression`` yields a function object. The unnamed object
1267behaves like a function object defined with ::
1268
1269 def name(arguments):
1270 return expression
1271
1272See section :ref:`function` for the syntax of parameter lists. Note that
1273functions created with lambda forms cannot contain statements.
1274
Georg Brandl8ec7f652007-08-15 14:28:01 +00001275
1276.. _exprlists:
1277
1278Expression lists
1279================
1280
1281.. index:: pair: expression; list
1282
1283.. productionlist::
1284 expression_list: `expression` ( "," `expression` )* [","]
1285
1286.. index:: object: tuple
1287
1288An expression list containing at least one comma yields a tuple. The length of
1289the tuple is the number of expressions in the list. The expressions are
1290evaluated from left to right.
1291
1292.. index:: pair: trailing; comma
1293
1294The trailing comma is required only to create a single tuple (a.k.a. a
1295*singleton*); it is optional in all other cases. A single expression without a
1296trailing comma doesn't create a tuple, but rather yields the value of that
1297expression. (To create an empty tuple, use an empty pair of parentheses:
1298``()``.)
1299
1300
1301.. _evalorder:
1302
1303Evaluation order
1304================
1305
1306.. index:: pair: evaluation; order
1307
1308Python evaluates expressions from left to right. Notice that while evaluating an
1309assignment, the right-hand side is evaluated before the left-hand side.
1310
1311In the following lines, expressions will be evaluated in the arithmetic order of
1312their suffixes::
1313
1314 expr1, expr2, expr3, expr4
1315 (expr1, expr2, expr3, expr4)
1316 {expr1: expr2, expr3: expr4}
1317 expr1 + expr2 * (expr3 - expr4)
Georg Brandl463f39d2008-08-08 06:42:20 +00001318 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001319 expr3, expr4 = expr1, expr2
1320
1321
1322.. _operator-summary:
1323
1324Summary
1325=======
1326
1327.. index:: pair: operator; precedence
1328
1329The following table summarizes the operator precedences in Python, from lowest
1330precedence (least binding) to highest precedence (most binding). Operators in
1331the same box have the same precedence. Unless the syntax is explicitly given,
1332operators are binary. Operators in the same box group left to right (except for
1333comparisons, including tests, which all have the same precedence and chain from
1334left to right --- see section :ref:`comparisons` --- and exponentiation, which
1335groups from right to left).
1336
1337+-----------------------------------------------+-------------------------------------+
1338| Operator | Description |
1339+===============================================+=====================================+
1340| :keyword:`lambda` | Lambda expression |
1341+-----------------------------------------------+-------------------------------------+
Georg Brandl38c72032010-03-07 21:12:28 +00001342| :keyword:`if` -- :keyword:`else` | Conditional expression |
1343+-----------------------------------------------+-------------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001344| :keyword:`or` | Boolean OR |
1345+-----------------------------------------------+-------------------------------------+
1346| :keyword:`and` | Boolean AND |
1347+-----------------------------------------------+-------------------------------------+
1348| :keyword:`not` *x* | Boolean NOT |
1349+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001350| :keyword:`in`, :keyword:`not` :keyword:`in`, | Comparisons, including membership |
1351| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests, |
1352| ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==`` | |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001353+-----------------------------------------------+-------------------------------------+
1354| ``|`` | Bitwise OR |
1355+-----------------------------------------------+-------------------------------------+
1356| ``^`` | Bitwise XOR |
1357+-----------------------------------------------+-------------------------------------+
1358| ``&`` | Bitwise AND |
1359+-----------------------------------------------+-------------------------------------+
1360| ``<<``, ``>>`` | Shifts |
1361+-----------------------------------------------+-------------------------------------+
1362| ``+``, ``-`` | Addition and subtraction |
1363+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001364| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001365+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001366| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001367+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001368| ``**`` | Exponentiation [#]_ |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001369+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001370| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1371| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001372+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001373| ``(expressions...)``, | Binding or tuple display, |
1374| ``[expressions...]``, | list display, |
1375| ``{key:datum...}``, | dictionary display, |
1376| ```expressions...``` | string conversion |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001377+-----------------------------------------------+-------------------------------------+
1378
1379.. rubric:: Footnotes
1380
Martin v. Löwis0b667312008-05-23 19:33:13 +00001381.. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001382 variables of each ``for`` it contains into the containing scope. However, this
Martin v. Löwis0b667312008-05-23 19:33:13 +00001383 behavior is deprecated, and relying on it will not work in Python 3.0
Georg Brandl8ec7f652007-08-15 14:28:01 +00001384
1385.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1386 true numerically due to roundoff. For example, and assuming a platform on which
1387 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1388 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1389 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod`
1390 in the :mod:`math` module returns a result whose sign matches the sign of the
1391 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1392 is more appropriate depends on the application.
1393
1394.. [#] If x is very close to an exact integer multiple of y, it's possible for
1395 ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding. In such
1396 cases, Python returns the latter result, in order to preserve that
1397 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1398
Mark Summerfield216ad332007-08-16 10:09:22 +00001399.. [#] While comparisons between unicode strings make sense at the byte
1400 level, they may be counter-intuitive to users. For example, the
Mark Summerfieldd92e8712007-10-03 08:53:21 +00001401 strings ``u"\u00C7"`` and ``u"\u0043\u0327"`` compare differently,
Mark Summerfield216ad332007-08-16 10:09:22 +00001402 even though they both represent the same unicode character (LATIN
Georg Brandl6eba7792010-04-02 08:51:31 +00001403 CAPITAL LETTER C WITH CEDILLA). To compare strings in a human
Mark Summerfieldd92e8712007-10-03 08:53:21 +00001404 recognizable way, compare using :func:`unicodedata.normalize`.
Mark Summerfield216ad332007-08-16 10:09:22 +00001405
Georg Brandl8ec7f652007-08-15 14:28:01 +00001406.. [#] The implementation computes this efficiently, without constructing lists or
1407 sorting.
1408
1409.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
1410 value) lists, but this was very expensive for the common case of comparing for
1411 equality. An even earlier version of Python compared dictionaries by identity
1412 only, but this caused surprises because people expected to be able to test a
1413 dictionary for emptiness by comparing it to ``{}``.
1414
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001415.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Georg Brandl3214a012008-07-01 20:50:02 +00001416 descriptors, you may notice seemingly unusual behaviour in certain uses of
1417 the :keyword:`is` operator, like those involving comparisons between instance
1418 methods, or constants. Check their documentation for more info.
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001419
1420.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1421 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.