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