blob: ef71a80f14584643a34e1b77bb1fecee20e44183 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
34.. XXX no coercion rules are documented anymore
35
36When a description of an arithmetic operator below uses the phrase "the numeric
37arguments are converted to a common type," the arguments are coerced using the
38coercion rules. If both arguments are standard
39numeric types, the following coercions are applied:
40
41* If either argument is a complex number, the other is converted to complex;
42
43* otherwise, if either argument is a floating point number, the other is
44 converted to floating point;
45
46* otherwise, if either argument is a long integer, the other is converted to
47 long integer;
48
49* otherwise, both must be plain integers and no conversion is necessary.
50
51Some additional rules apply for certain operators (e.g., a string left argument
52to the '%' operator). Extensions can define their own coercions.
53
54
55.. _atoms:
56
57Atoms
58=====
59
60.. index:: single: atom
61
62Atoms are the most basic elements of expressions. The simplest atoms are
63identifiers or literals. Forms enclosed in reverse quotes or in parentheses,
64brackets or braces are also categorized syntactically as atoms. The syntax for
65atoms is:
66
67.. productionlist::
68 atom: `identifier` | `literal` | `enclosure`
69 enclosure: `parenth_form` | `list_display`
70 : | `generator_expression` | `dict_display`
71 : | `string_conversion` | `yield_atom`
72
73
74.. _atom-identifiers:
75
76Identifiers (Names)
77-------------------
78
79.. index::
80 single: name
81 single: identifier
82
83An identifier occurring as an atom is a name. See section :ref:`identifiers`
84for lexical definition and section :ref:`naming` for documentation of naming and
85binding.
86
87.. index:: exception: NameError
88
89When the name is bound to an object, evaluation of the atom yields that object.
90When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
91exception.
92
93.. index::
94 pair: name; mangling
95 pair: private; names
96
97**Private name mangling:** When an identifier that textually occurs in a class
98definition begins with two or more underscore characters and does not end in two
99or more underscores, it is considered a :dfn:`private name` of that class.
100Private names are transformed to a longer form before code is generated for
101them. The transformation inserts the class name in front of the name, with
102leading underscores removed, and a single underscore inserted in front of the
103class name. For example, the identifier ``__spam`` occurring in a class named
104``Ham`` will be transformed to ``_Ham__spam``. This transformation is
105independent of the syntactical context in which the identifier is used. If the
106transformed name is extremely long (longer than 255 characters), implementation
107defined truncation may happen. If the class name consists only of underscores,
108no transformation is done.
109
110.. %
111.. %
112
113
114.. _atom-literals:
115
116Literals
117--------
118
119.. index:: single: literal
120
121Python supports string literals and various numeric literals:
122
123.. productionlist::
124 literal: `stringliteral` | `integer` | `longinteger`
125 : | `floatnumber` | `imagnumber`
126
127Evaluation of a literal yields an object of the given type (string, integer,
128long integer, floating point number, complex number) with the given value. The
129value may be approximated in the case of floating point and imaginary (complex)
130literals. See section :ref:`literals` for details.
131
132.. index::
133 triple: immutable; data; type
134 pair: immutable; object
135
136All literals correspond to immutable data types, and hence the object's identity
137is less important than its value. Multiple evaluations of literals with the
138same value (either the same occurrence in the program text or a different
139occurrence) may obtain the same object or a different object with the same
140value.
141
142
143.. _parenthesized:
144
145Parenthesized forms
146-------------------
147
148.. index:: single: parenthesized form
149
150A parenthesized form is an optional expression list enclosed in parentheses:
151
152.. productionlist::
153 parenth_form: "(" [`expression_list`] ")"
154
155A parenthesized expression list yields whatever that expression list yields: if
156the list contains at least one comma, it yields a tuple; otherwise, it yields
157the single expression that makes up the expression list.
158
159.. index:: pair: empty; tuple
160
161An empty pair of parentheses yields an empty tuple object. Since tuples are
162immutable, the rules for literals apply (i.e., two occurrences of the empty
163tuple may or may not yield the same object).
164
165.. index::
166 single: comma
167 pair: tuple; display
168
169Note that tuples are not formed by the parentheses, but rather by use of the
170comma operator. The exception is the empty tuple, for which parentheses *are*
171required --- allowing unparenthesized "nothing" in expressions would cause
172ambiguities and allow common typos to pass uncaught.
173
174
175.. _lists:
176
177List displays
178-------------
179
180.. index::
181 pair: list; display
182 pair: list; comprehensions
183
184A list display is a possibly empty series of expressions enclosed in square
185brackets:
186
187.. productionlist::
188 list_display: "[" [`expression_list` | `list_comprehension`] "]"
189 list_comprehension: `expression` `list_for`
190 list_for: "for" `target_list` "in" `old_expression_list` [`list_iter`]
191 old_expression_list: `old_expression` [("," `old_expression`)+ [","]]
192 list_iter: `list_for` | `list_if`
193 list_if: "if" `old_expression` [`list_iter`]
194
195.. index::
196 pair: list; comprehensions
197 object: list
198 pair: empty; list
199
200A list display yields a new list object. Its contents are specified by
201providing either a list of expressions or a list comprehension. When a
202comma-separated list of expressions is supplied, its elements are evaluated from
203left to right and placed into the list object in that order. When a list
204comprehension is supplied, it consists of a single expression followed by at
205least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if`
206clauses. In this case, the elements of the new list are those that would be
207produced by considering each of the :keyword:`for` or :keyword:`if` clauses a
208block, nesting from left to right, and evaluating the expression to produce a
209list element each time the innermost block is reached [#]_.
210
211
212.. _genexpr:
213
214Generator expressions
215---------------------
216
217.. index:: pair: generator; expression
218
219A generator expression is a compact generator notation in parentheses:
220
221.. productionlist::
222 generator_expression: "(" `expression` `genexpr_for` ")"
223 genexpr_for: "for" `target_list` "in" `or_test` [`genexpr_iter`]
224 genexpr_iter: `genexpr_for` | `genexpr_if`
225 genexpr_if: "if" `old_expression` [`genexpr_iter`]
226
227.. index:: object: generator
228
229A generator expression yields a new generator object. It consists of a single
230expression followed by at least one :keyword:`for` clause and zero or more
231:keyword:`for` or :keyword:`if` clauses. The iterating values of the new
232generator are those that would be produced by considering each of the
233:keyword:`for` or :keyword:`if` clauses a block, nesting from left to right, and
234evaluating the expression to yield a value that is reached the innermost block
235for each iteration.
236
237Variables used in the generator expression are evaluated lazily when the
238:meth:`__next__` method is called for generator object (in the same fashion as
239normal generators). However, the leftmost :keyword:`for` clause is immediately
240evaluated so that error produced by it can be seen before any other possible
241error in the code that handles the generator expression. Subsequent
242:keyword:`for` clauses cannot be evaluated immediately since they may depend on
243the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y
244in bar(x))``.
245
246The parentheses can be omitted on calls with only one argument. See section
247:ref:`calls` for the detail.
248
249
250.. _dict:
251
252Dictionary displays
253-------------------
254
255.. index:: pair: dictionary; display
256
257.. index::
258 single: key
259 single: datum
260 single: key/datum pair
261
262A dictionary display is a possibly empty series of key/datum pairs enclosed in
263curly braces:
264
265.. productionlist::
266 dict_display: "{" [`key_datum_list`] "}"
267 key_datum_list: `key_datum` ("," `key_datum`)* [","]
268 key_datum: `expression` ":" `expression`
269
270.. index:: object: dictionary
271
272A dictionary display yields a new dictionary object.
273
274The key/datum pairs are evaluated from left to right to define the entries of
275the dictionary: each key object is used as a key into the dictionary to store
276the corresponding datum.
277
278.. index:: pair: immutable; object
279
280Restrictions on the types of the key values are listed earlier in section
281:ref:`types`. (To summarize, the key type should be hashable, which excludes
282all mutable objects.) Clashes between duplicate keys are not detected; the last
283datum (textually rightmost in the display) stored for a given key value
284prevails.
285
286
287.. _yieldexpr:
288
289Yield expressions
290-----------------
291
292.. index::
293 keyword: yield
294 pair: yield; expression
295 pair: generator; function
296
297.. productionlist::
298 yield_atom: "(" `yield_expression` ")"
299 yield_expression: "yield" [`expression_list`]
300
301.. versionadded:: 2.5
302
303The :keyword:`yield` expression is only used when defining a generator function,
304and can only be used in the body of a function definition. Using a
305:keyword:`yield` expression in a function definition is sufficient to cause that
306definition to create a generator function instead of a normal function.
307
308When a generator function is called, it returns an iterator known as a
309generator. That generator then controls the execution of a generator function.
310The execution starts when one of the generator's methods is called. At that
311time, the execution proceeds to the first :keyword:`yield` expression, where it
312is suspended again, returning the value of :token:`expression_list` to
313generator's caller. By suspended we mean that all local state is retained,
314including the current bindings of local variables, the instruction pointer, and
315the internal evaluation stack. When the execution is resumed by calling one of
316the generator's methods, the function can proceed exactly as if the
317:keyword:`yield` expression was just another external call. The value of the
318:keyword:`yield` expression after resuming depends on the method which resumed
319the execution.
320
321.. index:: single: coroutine
322
323All of this makes generator functions quite similar to coroutines; they yield
324multiple times, they have more than one entry point and their execution can be
325suspended. The only difference is that a generator function cannot control
326where should the execution continue after it yields; the control is always
327transfered to the generator's caller.
328
329.. index:: object: generator
330
331The following generator's methods can be used to control the execution of a
332generator function:
333
334.. index:: exception: StopIteration
335
336
337.. method:: generator.next()
338
339 Starts the execution of a generator function or resumes it at the last executed
340 :keyword:`yield` expression. When a generator function is resumed with a
341 :meth:`next` method, the current :keyword:`yield` expression always evaluates to
342 :const:`None`. The execution then continues to the next :keyword:`yield`
343 expression, where the generator is suspended again, and the value of the
344 :token:`expression_list` is returned to :meth:`next`'s caller. If the generator
345 exits without yielding another value, a :exc:`StopIteration` exception is
346 raised.
347
348
349.. method:: generator.send(value)
350
351 Resumes the execution and "sends" a value into the generator function. The
352 ``value`` argument becomes the result of the current :keyword:`yield`
353 expression. The :meth:`send` method returns the next value yielded by the
354 generator, or raises :exc:`StopIteration` if the generator exits without
355 yielding another value. When :meth:`send` is called to start the generator, it
356 must be called with :const:`None` as the argument, because there is no
357 :keyword:`yield` expression that could receieve the value.
358
359
360.. method:: generator.throw(type[, value[, traceback]])
361
362 Raises an exception of type ``type`` at the point where generator was paused,
363 and returns the next value yielded by the generator function. If the generator
364 exits without yielding another value, a :exc:`StopIteration` exception is
365 raised. If the generator function does not catch the passed-in exception, or
366 raises a different exception, then that exception propagates to the caller.
367
368.. index:: exception: GeneratorExit
369
370
371.. method:: generator.close()
372
373 Raises a :exc:`GeneratorExit` at the point where the generator function was
374 paused. If the generator function then raises :exc:`StopIteration` (by exiting
375 normally, or due to already being closed) or :exc:`GeneratorExit` (by not
376 catching the exception), close returns to its caller. If the generator yields a
377 value, a :exc:`RuntimeError` is raised. If the generator raises any other
378 exception, it is propagated to the caller. :meth:`close` does nothing if the
379 generator has already exited due to an exception or normal exit.
380
381Here is a simple example that demonstrates the behavior of generators and
382generator functions::
383
384 >>> def echo(value=None):
385 ... print "Execution starts when 'next()' is called for the first time."
386 ... try:
387 ... while True:
388 ... try:
389 ... value = (yield value)
390 ... except GeneratorExit:
391 ... # never catch GeneratorExit
392 ... raise
393 ... except Exception, e:
394 ... value = e
395 ... finally:
396 ... print "Don't forget to clean up when 'close()' is called."
397 ...
398 >>> generator = echo(1)
399 >>> print generator.next()
400 Execution starts when 'next()' is called for the first time.
401 1
402 >>> print generator.next()
403 None
404 >>> print generator.send(2)
405 2
406 >>> generator.throw(TypeError, "spam")
407 TypeError('spam',)
408 >>> generator.close()
409 Don't forget to clean up when 'close()' is called.
410
411
412.. seealso::
413
414 :pep:`0342` - Coroutines via Enhanced Generators
415 The proposal to enhance the API and syntax of generators, making them usable as
416 simple coroutines.
417
418
419.. _primaries:
420
421Primaries
422=========
423
424.. index:: single: primary
425
426Primaries represent the most tightly bound operations of the language. Their
427syntax is:
428
429.. productionlist::
430 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
431
432
433.. _attribute-references:
434
435Attribute references
436--------------------
437
438.. index:: pair: attribute; reference
439
440An attribute reference is a primary followed by a period and a name:
441
442.. productionlist::
443 attributeref: `primary` "." `identifier`
444
445.. index::
446 exception: AttributeError
447 object: module
448 object: list
449
450The primary must evaluate to an object of a type that supports attribute
451references, e.g., a module, list, or an instance. This object is then asked to
452produce the attribute whose name is the identifier. If this attribute is not
453available, the exception :exc:`AttributeError` is raised. Otherwise, the type
454and value of the object produced is determined by the object. Multiple
455evaluations of the same attribute reference may yield different objects.
456
457
458.. _subscriptions:
459
460Subscriptions
461-------------
462
463.. index:: single: subscription
464
465.. index::
466 object: sequence
467 object: mapping
468 object: string
469 object: tuple
470 object: list
471 object: dictionary
472 pair: sequence; item
473
474A subscription selects an item of a sequence (string, tuple or list) or mapping
475(dictionary) object:
476
477.. productionlist::
478 subscription: `primary` "[" `expression_list` "]"
479
480The primary must evaluate to an object of a sequence or mapping type.
481
482If the primary is a mapping, the expression list must evaluate to an object
483whose value is one of the keys of the mapping, and the subscription selects the
484value in the mapping that corresponds to that key. (The expression list is a
485tuple except if it has exactly one item.)
486
487If the primary is a sequence, the expression (list) must evaluate to a plain
488integer. If this value is negative, the length of the sequence is added to it
489(so that, e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value
490must be a nonnegative integer less than the number of items in the sequence, and
491the subscription selects the item whose index is that value (counting from
492zero).
493
494.. index::
495 single: character
496 pair: string; item
497
498A string's items are characters. A character is not a separate data type but a
499string of exactly one character.
500
501
502.. _slicings:
503
504Slicings
505--------
506
507.. index::
508 single: slicing
509 single: slice
510
511.. index::
512 object: sequence
513 object: string
514 object: tuple
515 object: list
516
517A slicing selects a range of items in a sequence object (e.g., a string, tuple
518or list). Slicings may be used as expressions or as targets in assignment or
519:keyword:`del` statements. The syntax for a slicing:
520
521.. productionlist::
522 slicing: `simple_slicing` | `extended_slicing`
523 simple_slicing: `primary` "[" `short_slice` "]"
524 extended_slicing: `primary` "[" `slice_list` "]"
525 slice_list: `slice_item` ("," `slice_item`)* [","]
526 slice_item: `expression` | `proper_slice` | `ellipsis`
527 proper_slice: `short_slice` | `long_slice`
528 short_slice: [`lower_bound`] ":" [`upper_bound`]
529 long_slice: `short_slice` ":" [`stride`]
530 lower_bound: `expression`
531 upper_bound: `expression`
532 stride: `expression`
533 ellipsis: "..."
534
535.. index:: pair: extended; slicing
536
537There is ambiguity in the formal syntax here: anything that looks like an
538expression list also looks like a slice list, so any subscription can be
539interpreted as a slicing. Rather than further complicating the syntax, this is
540disambiguated by defining that in this case the interpretation as a subscription
541takes priority over the interpretation as a slicing (this is the case if the
542slice list contains no proper slice nor ellipses). Similarly, when the slice
543list has exactly one short slice and no trailing comma, the interpretation as a
544simple slicing takes priority over that as an extended slicing.
545
546The semantics for a simple slicing are as follows. The primary must evaluate to
547a sequence object. The lower and upper bound expressions, if present, must
548evaluate to plain integers; defaults are zero and the ``sys.maxint``,
549respectively. If either bound is negative, the sequence's length is added to
550it. The slicing now selects all items with index *k* such that ``i <= k < j``
551where *i* and *j* are the specified lower and upper bounds. This may be an
552empty sequence. It is not an error if *i* or *j* lie outside the range of valid
553indexes (such items don't exist so they aren't selected).
554
555.. index::
556 single: start (slice object attribute)
557 single: stop (slice object attribute)
558 single: step (slice object attribute)
559
560The semantics for an extended slicing are as follows. The primary must evaluate
561to a mapping object, and it is indexed with a key that is constructed from the
562slice list, as follows. If the slice list contains at least one comma, the key
563is a tuple containing the conversion of the slice items; otherwise, the
564conversion of the lone slice item is the key. The conversion of a slice item
565that is an expression is that expression. The conversion of a proper slice is a
566slice object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
567:attr:`step` attributes are the values of the expressions given as lower bound,
568upper bound and stride, respectively, substituting ``None`` for missing
569expressions.
570
571
572.. _calls:
573
574Calls
575-----
576
577.. index:: single: call
578
579.. index:: object: callable
580
581A call calls a callable object (e.g., a function) with a possibly empty series
582of arguments:
583
584.. productionlist::
585 call: `primary` "(" [`argument_list` [","]
586 : | `expression` `genexpr_for`] ")"
587 argument_list: `positional_arguments` ["," `keyword_arguments`]
588 : ["," "*" `expression`]
589 : ["," "**" `expression`]
590 : | `keyword_arguments` ["," "*" `expression`]
591 : ["," "**" `expression`]
592 : | "*" `expression` ["," "**" `expression`]
593 : | "**" `expression`
594 positional_arguments: `expression` ("," `expression`)*
595 keyword_arguments: `keyword_item` ("," `keyword_item`)*
596 keyword_item: `identifier` "=" `expression`
597
598A trailing comma may be present after the positional and keyword arguments but
599does not affect the semantics.
600
601The primary must evaluate to a callable object (user-defined functions, built-in
602functions, methods of built-in objects, class objects, methods of class
603instances, and certain class instances themselves are callable; extensions may
604define additional callable object types). All argument expressions are
605evaluated before the call is attempted. Please refer to section :ref:`function`
606for the syntax of formal parameter lists.
607
608If keyword arguments are present, they are first converted to positional
609arguments, as follows. First, a list of unfilled slots is created for the
610formal parameters. If there are N positional arguments, they are placed in the
611first N slots. Next, for each keyword argument, the identifier is used to
612determine the corresponding slot (if the identifier is the same as the first
613formal parameter name, the first slot is used, and so on). If the slot is
614already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
615the argument is placed in the slot, filling it (even if the expression is
616``None``, it fills the slot). When all arguments have been processed, the slots
617that are still unfilled are filled with the corresponding default value from the
618function definition. (Default values are calculated, once, when the function is
619defined; thus, a mutable object such as a list or dictionary used as default
620value will be shared by all calls that don't specify an argument value for the
621corresponding slot; this should usually be avoided.) If there are any unfilled
622slots for which no default value is specified, a :exc:`TypeError` exception is
623raised. Otherwise, the list of filled slots is used as the argument list for
624the call.
625
626If there are more positional arguments than there are formal parameter slots, a
627:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
628``*identifier`` is present; in this case, that formal parameter receives a tuple
629containing the excess positional arguments (or an empty tuple if there were no
630excess positional arguments).
631
632If any keyword argument does not correspond to a formal parameter name, a
633:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
634``**identifier`` is present; in this case, that formal parameter receives a
635dictionary containing the excess keyword arguments (using the keywords as keys
636and the argument values as corresponding values), or a (new) empty dictionary if
637there were no excess keyword arguments.
638
639If the syntax ``*expression`` appears in the function call, ``expression`` must
640evaluate to a sequence. Elements from this sequence are treated as if they were
641additional positional arguments; if there are postional arguments *x1*,...,*xN*
642, and ``expression`` evaluates to a sequence *y1*,...,*yM*, this is equivalent
643to a call with M+N positional arguments *x1*,...,*xN*,*y1*,...,*yM*.
644
645A consequence of this is that although the ``*expression`` syntax appears
646*after* any keyword arguments, it is processed *before* the keyword arguments
647(and the ``**expression`` argument, if any -- see below). So::
648
649 >>> def f(a, b):
650 ... print a, b
651 ...
652 >>> f(b=1, *(2,))
653 2 1
654 >>> f(a=1, *(2,))
655 Traceback (most recent call last):
656 File "<stdin>", line 1, in ?
657 TypeError: f() got multiple values for keyword argument 'a'
658 >>> f(1, *(2,))
659 1 2
660
661It is unusual for both keyword arguments and the ``*expression`` syntax to be
662used in the same call, so in practice this confusion does not arise.
663
664If the syntax ``**expression`` appears in the function call, ``expression`` must
665evaluate to a mapping, the contents of which are treated as additional keyword
666arguments. In the case of a keyword appearing in both ``expression`` and as an
667explicit keyword argument, a :exc:`TypeError` exception is raised.
668
669Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
670used as positional argument slots or as keyword argument names.
671
672A call always returns some value, possibly ``None``, unless it raises an
673exception. How this value is computed depends on the type of the callable
674object.
675
676If it is---
677
678a user-defined function:
679 .. index::
680 pair: function; call
681 triple: user-defined; function; call
682 object: user-defined function
683 object: function
684
685 The code block for the function is executed, passing it the argument list. The
686 first thing the code block will do is bind the formal parameters to the
687 arguments; this is described in section :ref:`function`. When the code block
688 executes a :keyword:`return` statement, this specifies the return value of the
689 function call.
690
691a built-in function or method:
692 .. index::
693 pair: function; call
694 pair: built-in function; call
695 pair: method; call
696 pair: built-in method; call
697 object: built-in method
698 object: built-in function
699 object: method
700 object: function
701
702 The result is up to the interpreter; see :ref:`built-in-funcs` for the
703 descriptions of built-in functions and methods.
704
705a class object:
706 .. index::
707 object: class
708 pair: class object; call
709
710 A new instance of that class is returned.
711
712a class instance method:
713 .. index::
714 object: class instance
715 object: instance
716 pair: class instance; call
717
718 The corresponding user-defined function is called, with an argument list that is
719 one longer than the argument list of the call: the instance becomes the first
720 argument.
721
722a class instance:
723 .. index::
724 pair: instance; call
725 single: __call__() (object method)
726
727 The class must define a :meth:`__call__` method; the effect is then the same as
728 if that method was called.
729
730
731.. _power:
732
733The power operator
734==================
735
736The power operator binds more tightly than unary operators on its left; it binds
737less tightly than unary operators on its right. The syntax is:
738
739.. productionlist::
740 power: `primary` ["**" `u_expr`]
741
742Thus, in an unparenthesized sequence of power and unary operators, the operators
743are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +0000744for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000745
746The power operator has the same semantics as the built-in :func:`pow` function,
747when called with two arguments: it yields its left argument raised to the power
748of its right argument. The numeric arguments are first converted to a common
749type. The result type is that of the arguments after coercion.
750
751With mixed operand types, the coercion rules for binary arithmetic operators
752apply. For int and long int operands, the result has the same type as the
753operands (after coercion) unless the second argument is negative; in that case,
754all arguments are converted to float and a float result is delivered. For
755example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last
756feature was added in Python 2.2. In Python 2.1 and before, if both arguments
757were of integer types and the second argument was negative, an exception was
758raised).
759
760Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
761Raising a negative number to a fractional power results in a :exc:`ValueError`.
762
763
764.. _unary:
765
766Unary arithmetic operations
767===========================
768
769.. index::
770 triple: unary; arithmetic; operation
771 triple: unary; bit-wise; operation
772
773All unary arithmetic (and bit-wise) operations have the same priority:
774
775.. productionlist::
776 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
777
778.. index::
779 single: negation
780 single: minus
781
782The unary ``-`` (minus) operator yields the negation of its numeric argument.
783
784.. index:: single: plus
785
786The unary ``+`` (plus) operator yields its numeric argument unchanged.
787
788.. index:: single: inversion
789
790The unary ``~`` (invert) operator yields the bit-wise inversion of its plain or
791long integer argument. The bit-wise inversion of ``x`` is defined as
792``-(x+1)``. It only applies to integral numbers.
793
794.. index:: exception: TypeError
795
796In all three cases, if the argument does not have the proper type, a
797:exc:`TypeError` exception is raised.
798
799
800.. _binary:
801
802Binary arithmetic operations
803============================
804
805.. index:: triple: binary; arithmetic; operation
806
807The binary arithmetic operations have the conventional priority levels. Note
808that some of these operations also apply to certain non-numeric types. Apart
809from the power operator, there are only two levels, one for multiplicative
810operators and one for additive operators:
811
812.. productionlist::
813 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
814 : | `m_expr` "%" `u_expr`
815 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
816
817.. index:: single: multiplication
818
819The ``*`` (multiplication) operator yields the product of its arguments. The
820arguments must either both be numbers, or one argument must be an integer (plain
821or long) and the other must be a sequence. In the former case, the numbers are
822converted to a common type and then multiplied together. In the latter case,
823sequence repetition is performed; a negative repetition factor yields an empty
824sequence.
825
826.. index::
827 exception: ZeroDivisionError
828 single: division
829
830The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
831their arguments. The numeric arguments are first converted to a common type.
832Plain or long integer division yields an integer of the same type; the result is
833that of mathematical division with the 'floor' function applied to the result.
834Division by zero raises the :exc:`ZeroDivisionError` exception.
835
836.. index:: single: modulo
837
838The ``%`` (modulo) operator yields the remainder from the division of the first
839argument by the second. The numeric arguments are first converted to a common
840type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
841arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
842(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
843result with the same sign as its second operand (or zero); the absolute value of
844the result is strictly smaller than the absolute value of the second operand
845[#]_.
846
847The integer division and modulo operators are connected by the following
848identity: ``x == (x/y)*y + (x%y)``. Integer division and modulo are also
849connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y,
850x%y)``. These identities don't hold for floating point numbers; there similar
851identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
852``floor(x/y) - 1`` [#]_.
853
854In addition to performing the modulo operation on numbers, the ``%`` operator is
855also overloaded by string and unicode objects to perform string formatting (also
856known as interpolation). The syntax for string formatting is described in the
857Python Library Reference, section :ref:`string-formatting`.
858
859The floor division operator, the modulo operator, and the :func:`divmod`
860function are not defined for complex numbers. Instead, convert to a
861floating point number using the :func:`abs` function if appropriate.
862
863.. index:: single: addition
864
865The ``+`` (addition) operator yields the sum of its arguments. The arguments
866must either both be numbers or both sequences of the same type. In the former
867case, the numbers are converted to a common type and then added together. In
868the latter case, the sequences are concatenated.
869
870.. index:: single: subtraction
871
872The ``-`` (subtraction) operator yields the difference of its arguments. The
873numeric arguments are first converted to a common type.
874
875
876.. _shifting:
877
878Shifting operations
879===================
880
881.. index:: pair: shifting; operation
882
883The shifting operations have lower priority than the arithmetic operations:
884
885.. productionlist::
886 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
887
888These operators accept plain or long integers as arguments. The arguments are
889converted to a common type. They shift the first argument to the left or right
890by the number of bits given by the second argument.
891
892.. index:: exception: ValueError
893
894A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift
895by *n* bits is defined as multiplication with ``pow(2,n)``; for plain integers
896there is no overflow check so in that case the operation drops bits and flips
897the sign if the result is not less than ``pow(2,31)`` in absolute value.
898Negative shift counts raise a :exc:`ValueError` exception.
899
900
901.. _bitwise:
902
903Binary bit-wise operations
904==========================
905
906.. index:: triple: binary; bit-wise; operation
907
908Each of the three bitwise operations has a different priority level:
909
910.. productionlist::
911 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
912 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
913 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
914
915.. index:: pair: bit-wise; and
916
917The ``&`` operator yields the bitwise AND of its arguments, which must be plain
918or long integers. The arguments are converted to a common type.
919
920.. index::
921 pair: bit-wise; xor
922 pair: exclusive; or
923
924The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
925must be plain or long integers. The arguments are converted to a common type.
926
927.. index::
928 pair: bit-wise; or
929 pair: inclusive; or
930
931The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
932must be plain or long integers. The arguments are converted to a common type.
933
934
935.. _comparisons:
936
937Comparisons
938===========
939
940.. index:: single: comparison
941
942.. index:: pair: C; language
943
944Unlike C, all comparison operations in Python have the same priority, which is
945lower than that of any arithmetic, shifting or bitwise operation. Also unlike
946C, expressions like ``a < b < c`` have the interpretation that is conventional
947in mathematics:
948
949.. productionlist::
950 comparison: `or_expr` ( `comp_operator` `or_expr` )*
951 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
952 : | "is" ["not"] | ["not"] "in"
953
954Comparisons yield boolean values: ``True`` or ``False``.
955
956.. index:: pair: chaining; comparisons
957
958Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
959``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
960cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
961
Guido van Rossum04110fb2007-08-24 16:32:05 +0000962Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
963*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
964to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
965evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +0000966
Guido van Rossum04110fb2007-08-24 16:32:05 +0000967Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +0000968*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
969pretty).
970
971The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
972values of two objects. The objects need not have the same type. If both are
973numbers, they are converted to a common type. Otherwise, objects of different
974types *always* compare unequal, and are ordered consistently but arbitrarily.
975You can control comparison behavior of objects of non-builtin types by defining
976a ``__cmp__`` method or rich comparison methods like ``__gt__``, described in
977section :ref:`specialnames`.
978
979(This unusual definition of comparison was used to simplify the definition of
980operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
981In the future, the comparison rules for objects of different types are likely to
982change.)
983
984Comparison of objects of the same type depends on the type:
985
986* Numbers are compared arithmetically.
987
988* Strings are compared lexicographically using the numeric equivalents (the
989 result of the built-in function :func:`ord`) of their characters. Unicode and
Guido van Rossumda27fd22007-08-17 00:24:54 +0000990 8-bit strings are fully interoperable in this behavior. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +0000991
992* Tuples and lists are compared lexicographically using comparison of
993 corresponding elements. This means that to compare equal, each element must
994 compare equal and the two sequences must be of the same type and have the same
995 length.
996
997 If not equal, the sequences are ordered the same as their first differing
998 elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
999 ``cmp(x,y)``. If the corresponding element does not exist, the shorter sequence
1000 is ordered first (for example, ``[1,2] < [1,2,3]``).
1001
1002* Mappings (dictionaries) compare equal if and only if their sorted (key, value)
1003 lists compare equal. [#]_ Outcomes other than equality are resolved
1004 consistently, but are not otherwise defined. [#]_
1005
1006* Most other objects of builtin types compare unequal unless they are the same
1007 object; the choice whether one object is considered smaller or larger than
1008 another one is made arbitrarily but consistently within one execution of a
1009 program.
1010
1011The operators :keyword:`in` and :keyword:`not in` test for set membership. ``x
1012in s`` evaluates to true if *x* is a member of the set *s*, and false otherwise.
1013``x not in s`` returns the negation of ``x in s``. The set membership test has
1014traditionally been bound to sequences; an object is a member of a set if the set
1015is a sequence and contains an element equal to that object. However, it is
1016possible for an object to support membership tests without being a sequence. In
1017particular, dictionaries support membership testing as a nicer way of spelling
1018``key in dict``; other mapping types may follow suit.
1019
1020For the list and tuple types, ``x in y`` is true if and only if there exists an
1021index *i* such that ``x == y[i]`` is true.
1022
1023For the Unicode and string types, ``x in y`` is true if and only if *x* is a
1024substring of *y*. An equivalent test is ``y.find(x) != -1``. Note, *x* and *y*
1025need not be the same type; consequently, ``u'ab' in 'abc'`` will return
1026``True``. Empty strings are always considered to be a substring of any other
1027string, so ``"" in "abc"`` will return ``True``.
1028
1029.. versionchanged:: 2.3
1030 Previously, *x* was required to be a string of length ``1``.
1031
1032For user-defined classes which define the :meth:`__contains__` method, ``x in
1033y`` is true if and only if ``y.__contains__(x)`` is true.
1034
1035For user-defined classes which do not define :meth:`__contains__` and do define
1036:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1037integer index *i* such that ``x == y[i]``, and all lower integer indices do not
1038raise :exc:`IndexError` exception. (If any other exception is raised, it is as
1039if :keyword:`in` raised that exception).
1040
1041.. index::
1042 operator: in
1043 operator: not in
1044 pair: membership; test
1045 object: sequence
1046
1047The operator :keyword:`not in` is defined to have the inverse true value of
1048:keyword:`in`.
1049
1050.. index::
1051 operator: is
1052 operator: is not
1053 pair: identity; test
1054
1055The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1056is y`` is true if and only if *x* and *y* are the same object. ``x is not y``
1057yields the inverse truth value.
1058
1059
1060.. _booleans:
1061
1062Boolean operations
1063==================
1064
1065.. index::
1066 pair: Conditional; expression
1067 pair: Boolean; operation
1068
1069Boolean operations have the lowest priority of all Python operations:
1070
1071.. productionlist::
1072 expression: `conditional_expression` | `lambda_form`
1073 old_expression: `or_test` | `old_lambda_form`
1074 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1075 or_test: `and_test` | `or_test` "or" `and_test`
1076 and_test: `not_test` | `and_test` "and" `not_test`
1077 not_test: `comparison` | "not" `not_test`
1078
1079In the context of Boolean operations, and also when expressions are used by
1080control flow statements, the following values are interpreted as false:
1081``False``, ``None``, numeric zero of all types, and empty strings and containers
1082(including strings, tuples, lists, dictionaries, sets and frozensets). All
1083other values are interpreted as true.
1084
1085.. index:: operator: not
1086
1087The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1088otherwise.
1089
1090The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is
1091true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated
1092and its value is returned.
1093
1094.. versionadded:: 2.5
1095
1096.. index:: operator: and
1097
1098The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1099returned; otherwise, *y* is evaluated and the resulting value is returned.
1100
1101.. index:: operator: or
1102
1103The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1104returned; otherwise, *y* is evaluated and the resulting value is returned.
1105
1106(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1107they return to ``False`` and ``True``, but rather return the last evaluated
1108argument. This is sometimes useful, e.g., if ``s`` is a string that should be
1109replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1110the desired value. Because :keyword:`not` has to invent a value anyway, it does
1111not bother to return a value of the same type as its argument, so e.g., ``not
1112'foo'`` yields ``False``, not ``''``.)
1113
1114
1115.. _lambdas:
1116
1117Lambdas
1118=======
1119
1120.. index::
1121 pair: lambda; expression
1122 pair: lambda; form
1123 pair: anonymous; function
1124
1125.. productionlist::
1126 lambda_form: "lambda" [`parameter_list`]: `expression`
1127 old_lambda_form: "lambda" [`parameter_list`]: `old_expression`
1128
1129Lambda forms (lambda expressions) have the same syntactic position as
1130expressions. They are a shorthand to create anonymous functions; the expression
1131``lambda arguments: expression`` yields a function object. The unnamed object
1132behaves like a function object defined with ::
1133
1134 def name(arguments):
1135 return expression
1136
1137See section :ref:`function` for the syntax of parameter lists. Note that
1138functions created with lambda forms cannot contain statements or annotations.
1139
1140.. _lambda:
1141
1142
1143.. _exprlists:
1144
1145Expression lists
1146================
1147
1148.. index:: pair: expression; list
1149
1150.. productionlist::
1151 expression_list: `expression` ( "," `expression` )* [","]
1152
1153.. index:: object: tuple
1154
1155An expression list containing at least one comma yields a tuple. The length of
1156the tuple is the number of expressions in the list. The expressions are
1157evaluated from left to right.
1158
1159.. index:: pair: trailing; comma
1160
1161The trailing comma is required only to create a single tuple (a.k.a. a
1162*singleton*); it is optional in all other cases. A single expression without a
1163trailing comma doesn't create a tuple, but rather yields the value of that
1164expression. (To create an empty tuple, use an empty pair of parentheses:
1165``()``.)
1166
1167
1168.. _evalorder:
1169
1170Evaluation order
1171================
1172
1173.. index:: pair: evaluation; order
1174
1175Python evaluates expressions from left to right. Notice that while evaluating an
1176assignment, the right-hand side is evaluated before the left-hand side.
1177
1178In the following lines, expressions will be evaluated in the arithmetic order of
1179their suffixes::
1180
1181 expr1, expr2, expr3, expr4
1182 (expr1, expr2, expr3, expr4)
1183 {expr1: expr2, expr3: expr4}
1184 expr1 + expr2 * (expr3 - expr4)
1185 func(expr1, expr2, *expr3, **expr4)
1186 expr3, expr4 = expr1, expr2
1187
1188
1189.. _operator-summary:
1190
1191Summary
1192=======
1193
1194.. index:: pair: operator; precedence
1195
1196The following table summarizes the operator precedences in Python, from lowest
1197precedence (least binding) to highest precedence (most binding). Operators in
1198the same box have the same precedence. Unless the syntax is explicitly given,
1199operators are binary. Operators in the same box group left to right (except for
1200comparisons, including tests, which all have the same precedence and chain from
1201left to right --- see section :ref:`comparisons` --- and exponentiation, which
1202groups from right to left).
1203
1204+----------------------------------------------+-------------------------------------+
1205| Operator | Description |
1206+==============================================+=====================================+
1207| :keyword:`lambda` | Lambda expression |
1208+----------------------------------------------+-------------------------------------+
1209| :keyword:`or` | Boolean OR |
1210+----------------------------------------------+-------------------------------------+
1211| :keyword:`and` | Boolean AND |
1212+----------------------------------------------+-------------------------------------+
1213| :keyword:`not` *x* | Boolean NOT |
1214+----------------------------------------------+-------------------------------------+
1215| :keyword:`in`, :keyword:`not` :keyword:`in` | Membership tests |
1216+----------------------------------------------+-------------------------------------+
1217| :keyword:`is`, :keyword:`is not` | Identity tests |
1218+----------------------------------------------+-------------------------------------+
1219| ``<``, ``<=``, ``>``, ``>=``, ``!=``, ``==`` | Comparisons |
1220+----------------------------------------------+-------------------------------------+
1221| ``|`` | Bitwise OR |
1222+----------------------------------------------+-------------------------------------+
1223| ``^`` | Bitwise XOR |
1224+----------------------------------------------+-------------------------------------+
1225| ``&`` | Bitwise AND |
1226+----------------------------------------------+-------------------------------------+
1227| ``<<``, ``>>`` | Shifts |
1228+----------------------------------------------+-------------------------------------+
1229| ``+``, ``-`` | Addition and subtraction |
1230+----------------------------------------------+-------------------------------------+
1231| ``*``, ``/``, ``%`` | Multiplication, division, remainder |
1232+----------------------------------------------+-------------------------------------+
1233| ``+x``, ``-x`` | Positive, negative |
1234+----------------------------------------------+-------------------------------------+
1235| ``~x`` | Bitwise not |
1236+----------------------------------------------+-------------------------------------+
1237| ``**`` | Exponentiation |
1238+----------------------------------------------+-------------------------------------+
1239| ``x.attribute`` | Attribute reference |
1240+----------------------------------------------+-------------------------------------+
1241| ``x[index]`` | Subscription |
1242+----------------------------------------------+-------------------------------------+
1243| ``x[index:index]`` | Slicing |
1244+----------------------------------------------+-------------------------------------+
1245| ``f(arguments...)`` | Function call |
1246+----------------------------------------------+-------------------------------------+
1247| ``(expressions...)`` | Binding or tuple display |
1248+----------------------------------------------+-------------------------------------+
1249| ``[expressions...]`` | List display |
1250+----------------------------------------------+-------------------------------------+
1251| ``{key:datum...}`` | Dictionary display |
1252+----------------------------------------------+-------------------------------------+
1253
1254.. rubric:: Footnotes
1255
1256.. [#] In Python 2.3, a list comprehension "leaks" the control variables of each
1257 ``for`` it contains into the containing scope. However, this behavior is
1258 deprecated, and relying on it will not work once this bug is fixed in a future
1259 release
1260
1261.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1262 true numerically due to roundoff. For example, and assuming a platform on which
1263 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1264 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1265 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod`
1266 in the :mod:`math` module returns a result whose sign matches the sign of the
1267 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1268 is more appropriate depends on the application.
1269
1270.. [#] If x is very close to an exact integer multiple of y, it's possible for
1271 ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding. In such
1272 cases, Python returns the latter result, in order to preserve that
1273 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1274
Guido van Rossumda27fd22007-08-17 00:24:54 +00001275.. [#] While comparisons between unicode strings make sense at the byte
1276 level, they may be counter-intuitive to users. For example, the
1277 strings ``u"\u00C7"`` and ``u"\u0327\u0043"`` compare differently,
1278 even though they both represent the same unicode character (LATIN
1279 CAPTITAL LETTER C WITH CEDILLA).
1280
Georg Brandl116aa622007-08-15 14:28:22 +00001281.. [#] The implementation computes this efficiently, without constructing lists or
1282 sorting.
1283
1284.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
1285 value) lists, but this was very expensive for the common case of comparing for
1286 equality. An even earlier version of Python compared dictionaries by identity
1287 only, but this caused surprises because people expected to be able to test a
1288 dictionary for emptiness by comparing it to ``{}``.
1289