rest25/reference/expressions.rst => rest262/reference/expressions.rst
58.. index:: single: atom
59
60Atoms are the most basic elements of expressions.  The simplest atoms are
61identifiers or literals.  Forms enclosed in reverse quotes or in parentheses,
62brackets or braces are also categorized syntactically as atoms.  The syntax for
63atoms is:
64
65.. productionlist::
n66-   atom: `identifier` \| `literal` \| `enclosure`
n66+   atom: `identifier` | `literal` | `enclosure`
67-   enclosure: `parenth_form` \| `list_display`
67+   enclosure: `parenth_form` | `list_display`
68-            : \| `generator_expression` \| `dict_display`
68+            : | `generator_expression` | `dict_display`
69-            : \| `string_conversion`
69+            : | `string_conversion` | `yield_atom`
70
71
72.. _atom-identifiers:
73
74Identifiers (Names)
75-------------------
76
77.. index::
78   single: name
79   single: identifier
80
n81-An identifier occurring as an atom is a name.  See section :ref:`naming` for
n81+An identifier occurring as an atom is a name.  See section :ref:`identifiers`
82-documentation of naming and binding.
82+for lexical definition and section :ref:`naming` for documentation of naming and
83+binding.
83
84.. index:: exception: NameError
85
86When the name is bound to an object, evaluation of the atom yields that object.
87When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
88exception.
89
90.. index::
99leading underscores removed, and a single underscore inserted in front of the
100class name.  For example, the identifier ``__spam`` occurring in a class named
101``Ham`` will be transformed to ``_Ham__spam``.  This transformation is
102independent of the syntactical context in which the identifier is used.  If the
103transformed name is extremely long (longer than 255 characters), implementation
104defined truncation may happen.  If the class name consists only of underscores,
105no transformation is done.
106
n107-.. % 
108-.. % 
109
110
111.. _atom-literals:
112
113Literals
114--------
115
116.. index:: single: literal
117
118Python supports string literals and various numeric literals:
119
120.. productionlist::
n121-   literal: `stringliteral` \| `integer` \| `longinteger`
n120+   literal: `stringliteral` | `integer` | `longinteger`
122-          : \| `floatnumber` \| `imagnumber`
121+          : | `floatnumber` | `imagnumber`
123
124Evaluation of a literal yields an object of the given type (string, integer,
125long integer, floating point number, complex number) with the given value.  The
126value may be approximated in the case of floating point and imaginary (complex)
127literals.  See section :ref:`literals` for details.
128
129.. index::
130   triple: immutable; data; type
177.. index::
178   pair: list; display
179   pair: list; comprehensions
180
181A list display is a possibly empty series of expressions enclosed in square
182brackets:
183
184.. productionlist::
n185-   test: `or_test` \| `lambda_form`
n184+   list_display: "[" [`expression_list` | `list_comprehension`] "]"
186-   testlist: `test` ( "," `test` )\* [ "," ]
185+   list_comprehension: `expression` `list_for`
187-   list_display: "[" [`listmaker`] "]"
186+   list_for: "for" `target_list` "in" `old_expression_list` [`list_iter`]
188-   listmaker: `expression` ( `list_for` \| ( "," `expression` )\* [","] )
187+   old_expression_list: `old_expression` [("," `old_expression`)+ [","]]
189-   list_iter: `list_for` \| `list_if`
188+   list_iter: `list_for` | `list_if`
190-   list_for: "for" `expression_list` "in" `testlist` [`list_iter`]
191-   list_if: "if" `test` [`list_iter`]
189+   list_if: "if" `old_expression` [`list_iter`]
192
193.. index::
194   pair: list; comprehensions
195   object: list
196   pair: empty; list
197
198A list display yields a new list object.  Its contents are specified by
n199-providing either a list of expressions or a list comprehension.  When a comma-
n197+providing either a list of expressions or a list comprehension.  When a
200-separated list of expressions is supplied, its elements are evaluated from left
198+comma-separated list of expressions is supplied, its elements are evaluated from
201-to right and placed into the list object in that order.  When a list
199+left to right and placed into the list object in that order.  When a list
202comprehension is supplied, it consists of a single expression followed by at
203least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if`
204clauses.  In this case, the elements of the new list are those that would be
205produced by considering each of the :keyword:`for` or :keyword:`if` clauses a
206block, nesting from left to right, and evaluating the expression to produce a
207list element each time the innermost block is reached [#]_.
208
209
212Generator expressions
213---------------------
214
215.. index:: pair: generator; expression
216
217A generator expression is a compact generator notation in parentheses:
218
219.. productionlist::
n220-   generator_expression: "(" `test` `genexpr_for` ")"
n218+   generator_expression: "(" `expression` `genexpr_for` ")"
221-   genexpr_for: "for" `expression_list` "in" `test` [`genexpr_iter`]
219+   genexpr_for: "for" `target_list` "in" `or_test` [`genexpr_iter`]
222-   genexpr_iter: `genexpr_for` \| `genexpr_if`
220+   genexpr_iter: `genexpr_for` | `genexpr_if`
223-   genexpr_if: "if" `test` [`genexpr_iter`]
221+   genexpr_if: "if" `old_expression` [`genexpr_iter`]
224
n225-.. index::
226-   object: generator
223+.. index:: object: generator
227-   object: generator expression
228
n229-A generator expression yields a new generator object.   It consists of a single
n225+A 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
n237-Variables used in the generator expression are evaluated lazily whethe
n233+Variables used in the generator expression are evaluated lazily in a separate
238-:meth:`next` method is called for generator object (in the same fashion as
234+scope when the :meth:`next` method is called for the generator object (in the
239-normal generators). However, the leftmost :keyword:`for` clause is immediately
235+same fashion as for normal generators).  However, the :keyword:`in` expression
236+of the leftmost :keyword:`for` clause is immediately evaluated in the current
240-evaluated so that error produced by it can be seen before any other possible
237+scope so that an error produced by it can be seen before any other possible
241-error in the code that handles the generator expression. Subsequent
238+error in the code that handles the generator expression.  Subsequent
242-:keyword:`for` clauses cannot be evaluated immediately since they may depend on
239+:keyword:`for` and :keyword:`if` clauses cannot be evaluated immediately since
243-the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y
240+they may depend on the previous :keyword:`for` loop.  For example:
244-in bar(x))``.
241+``(x*y for x in range(10) for y in 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
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`] "}"
n267-   key_datum_list: `key_datum` ("," `key_datum`)\* [","]
n264+   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
n281-:ref:`types`.  (To summarize, the key type should be hashable, which excludes
n278+:ref:`types`.  (To summarize, the key type should be :term:`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.. _string-conversions:
288
289String conversions
324   builtin: repr
325   builtin: str
326
327The built-in function :func:`repr` performs exactly the same conversion in its
328argument as enclosing it in parentheses and reverse quotes does.  The built-in
329function :func:`str` performs a similar but more user-friendly conversion.
330
331
n329+.. _yieldexpr:
330+ 
331+Yield expressions
332+-----------------
333+ 
334+.. index::
335+   keyword: yield
336+   pair: yield; expression
337+   pair: generator; function
338+ 
339+.. productionlist::
340+   yield_atom: "(" `yield_expression` ")"
341+   yield_expression: "yield" [`expression_list`]
342+ 
343+.. versionadded:: 2.5
344+ 
345+The :keyword:`yield` expression is only used when defining a generator function,
346+and can only be used in the body of a function definition. Using a
347+:keyword:`yield` expression in a function definition is sufficient to cause that
348+definition to create a generator function instead of a normal function.
349+ 
350+When a generator function is called, it returns an iterator known as a
351+generator.  That generator then controls the execution of a generator function.
352+The execution starts when one of the generator's methods is called.  At that
353+time, the execution proceeds to the first :keyword:`yield` expression, where it
354+is suspended again, returning the value of :token:`expression_list` to
355+generator's caller.  By suspended we mean that all local state is retained,
356+including the current bindings of local variables, the instruction pointer, and
357+the internal evaluation stack.  When the execution is resumed by calling one of
358+the generator's methods, the function can proceed exactly as if the
359+:keyword:`yield` expression was just another external call. The value of the
360+:keyword:`yield` expression after resuming depends on the method which resumed
361+the execution.
362+ 
363+.. index:: single: coroutine
364+ 
365+All of this makes generator functions quite similar to coroutines; they yield
366+multiple times, they have more than one entry point and their execution can be
367+suspended.  The only difference is that a generator function cannot control
368+where should the execution continue after it yields; the control is always
369+transfered to the generator's caller.
370+ 
371+.. index:: object: generator
372+ 
373+The following generator's methods can be used to control the execution of a
374+generator function:
375+ 
376+.. index:: exception: StopIteration
377+ 
378+ 
379+.. method:: generator.next()
380+ 
381+   Starts the execution of a generator function or resumes it at the last executed
382+   :keyword:`yield` expression.  When a generator function is resumed with a
383+   :meth:`next` method, the current :keyword:`yield` expression always evaluates to
384+   :const:`None`.  The execution then continues to the next :keyword:`yield`
385+   expression, where the generator is suspended again, and the value of the
386+   :token:`expression_list` is returned to :meth:`next`'s caller. If the generator
387+   exits without yielding another value, a :exc:`StopIteration` exception is
388+   raised.
389+ 
390+ 
391+.. method:: generator.send(value)
392+ 
393+   Resumes the execution and "sends" a value into the generator function.  The
394+   ``value`` argument becomes the result of the current :keyword:`yield`
395+   expression.  The :meth:`send` method returns the next value yielded by the
396+   generator, or raises :exc:`StopIteration` if the generator exits without
397+   yielding another value. When :meth:`send` is called to start the generator, it
398+   must be called with :const:`None` as the argument, because there is no
399+   :keyword:`yield` expression that could receive the value.
400+ 
401+ 
402+.. method:: generator.throw(type[, value[, traceback]])
403+ 
404+   Raises an exception of type ``type`` at the point where generator was paused,
405+   and returns the next value yielded by the generator function.  If the generator
406+   exits without yielding another value, a :exc:`StopIteration` exception is
407+   raised.  If the generator function does not catch the passed-in exception, or
408+   raises a different exception, then that exception propagates to the caller.
409+ 
410+.. index:: exception: GeneratorExit
411+ 
412+ 
413+.. method:: generator.close()
414+ 
415+   Raises a :exc:`GeneratorExit` at the point where the generator function was
416+   paused.  If the generator function then raises :exc:`StopIteration` (by exiting
417+   normally, or due to already being closed) or :exc:`GeneratorExit` (by not
418+   catching the exception), close returns to its caller.  If the generator yields a
419+   value, a :exc:`RuntimeError` is raised.  If the generator raises any other
420+   exception, it is propagated to the caller.  :meth:`close` does nothing if the
421+   generator has already exited due to an exception or normal exit.
422+ 
423+Here is a simple example that demonstrates the behavior of generators and
424+generator functions::
425+ 
426+   >>> def echo(value=None):
427+   ...     print "Execution starts when 'next()' is called for the first time."
428+   ...     try:
429+   ...         while True:
430+   ...             try:
431+   ...                 value = (yield value)
432+   ...             except Exception, e:
433+   ...                 value = e
434+   ...     finally:
435+   ...         print "Don't forget to clean up when 'close()' is called."
436+   ...
437+   >>> generator = echo(1)
438+   >>> print generator.next()
439+   Execution starts when 'next()' is called for the first time.
440+   1
441+   >>> print generator.next()
442+   None
443+   >>> print generator.send(2)
444+   2
445+   >>> generator.throw(TypeError, "spam")
446+   TypeError('spam',)
447+   >>> generator.close()
448+   Don't forget to clean up when 'close()' is called.
449+ 
450+ 
451+.. seealso::
452+ 
453+   :pep:`0342` - Coroutines via Enhanced Generators
454+      The proposal to enhance the API and syntax of generators, making them usable as
455+      simple coroutines.
456+ 
457+ 
332.. _primaries:
333
334Primaries
335=========
336
337.. index:: single: primary
338
339Primaries represent the most tightly bound operations of the language. Their
340syntax is:
341
342.. productionlist::
n343-   primary: `atom` \| `attributeref` \| `subscription` \| `slicing` \| `call`
n469+   primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
344
345
346.. _attribute-references:
347
348Attribute references
349--------------------
350
351.. index:: pair: attribute; reference
427   object: tuple
428   object: list
429
430A slicing selects a range of items in a sequence object (e.g., a string, tuple
431or list).  Slicings may be used as expressions or as targets in assignment or
432:keyword:`del` statements.  The syntax for a slicing:
433
434.. productionlist::
n435-   slicing: `simple_slicing` \| `extended_slicing`
n561+   slicing: `simple_slicing` | `extended_slicing`
436   simple_slicing: `primary` "[" `short_slice` "]"
n437-   extended_slicing: `primary` "[" `slice_list` "]" 
n563+   extended_slicing: `primary` "[" `slice_list` "]"
438-   slice_list: `slice_item` ("," `slice_item`)\* [","]
564+   slice_list: `slice_item` ("," `slice_item`)* [","]
439-   slice_item: `expression` \| `proper_slice` \| `ellipsis`
565+   slice_item: `expression` | `proper_slice` | `ellipsis`
440-   proper_slice: `short_slice` \| `long_slice`
566+   proper_slice: `short_slice` | `long_slice`
441   short_slice: [`lower_bound`] ":" [`upper_bound`]
442   long_slice: `short_slice` ":" [`stride`]
443   lower_bound: `expression`
444   upper_bound: `expression`
445   stride: `expression`
446   ellipsis: "..."
447
448.. index:: pair: extended; slicing
491.. index:: single: call
492
493.. index:: object: callable
494
495A call calls a callable object (e.g., a function) with a possibly empty series
496of arguments:
497
498.. productionlist::
n499-   call: `primary` "(" [`argument_list` [","]] ")"
n625+   call: `primary` "(" [`argument_list` [","]
626+       : | `expression` `genexpr_for`] ")"
500   argument_list: `positional_arguments` ["," `keyword_arguments`]
n501-                : ["," "\*" `expression`]
n628+                :   ["," "*" `expression`] ["," `keyword_arguments`]
502-                : ["," "\*\*" `expression`]
629+                :   ["," "**" `expression`]
503-                : \| `keyword_arguments` ["," "\*" `expression`]
630+                : | `keyword_arguments` ["," "*" `expression`]
504-                : ["," "\*\*" `expression`]
631+                :   ["," "**" `expression`]
505-                : \| "\*" `expression` ["," "\*\*" `expression`]
632+                : | "*" `expression` ["," "*" `expression`] ["," "**" `expression`]
506-                : \| "\*\*" `expression`
633+                : | "**" `expression`
507-   positional_arguments: `expression` ("," `expression`)\*
634+   positional_arguments: `expression` ("," `expression`)*
508-   keyword_arguments: `keyword_item` ("," `keyword_item`)\*
635+   keyword_arguments: `keyword_item` ("," `keyword_item`)*
509   keyword_item: `identifier` "=" `expression`
510
511A trailing comma may be present after the positional and keyword arguments but
512does not affect the semantics.
513
514The primary must evaluate to a callable object (user-defined functions, built-in
515functions, methods of built-in objects, class objects, methods of class
516instances, and certain class instances themselves are callable; extensions may
531function definition.  (Default values are calculated, once, when the function is
532defined; thus, a mutable object such as a list or dictionary used as default
533value will be shared by all calls that don't specify an argument value for the
534corresponding slot; this should usually be avoided.)  If there are any unfilled
535slots for which no default value is specified, a :exc:`TypeError` exception is
536raised.  Otherwise, the list of filled slots is used as the argument list for
537the call.
538
n666+.. note::
667+ 
668+   An implementation may provide builtin functions whose positional parameters do
669+   not have names, even if they are 'named' for the purpose of documentation, and
670+   which therefore cannot be supplied by keyword.  In CPython, this is the case for
671+   functions implemented in C that use :cfunc:`PyArg_ParseTuple` to parse their
672+   arguments.
673+ 
539If there are more positional arguments than there are formal parameter slots, a
540:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
541``*identifier`` is present; in this case, that formal parameter receives a tuple
542containing the excess positional arguments (or an empty tuple if there were no
543excess positional arguments).
544
545If any keyword argument does not correspond to a formal parameter name, a
546:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
547``**identifier`` is present; in this case, that formal parameter receives a
548dictionary containing the excess keyword arguments (using the keywords as keys
549and the argument values as corresponding values), or a (new) empty dictionary if
550there were no excess keyword arguments.
551
552If the syntax ``*expression`` appears in the function call, ``expression`` must
553evaluate to a sequence.  Elements from this sequence are treated as if they were
n554-additional positional arguments; if there are postional arguments *x1*,...,*xN*
n689+additional positional arguments; if there are positional arguments *x1*,...,
555-, and ``expression`` evaluates to a sequence *y1*,...,*yM*, this is equivalent
690+*xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this is
556-to a call with M+N positional arguments *x1*,...,*xN*,*y1*,...,*yM*.
691+equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*, ...,
692+*yM*.
557
n558-A consequence of this is that although the ``*expression`` syntax appears
n694+A consequence of this is that although the ``*expression`` syntax may appear
559-*after* any keyword arguments, it is processed *before* the keyword arguments
695+*after* some keyword arguments, it is processed *before* the keyword arguments
560(and the ``**expression`` argument, if any -- see below).  So::
561
562   >>> def f(a, b):
563   ...  print a, b
564   ...
565   >>> f(b=1, *(2,))
566   2 1
567   >>> f(a=1, *(2,))
570   TypeError: f() got multiple values for keyword argument 'a'
571   >>> f(1, *(2,))
572   1 2
573
574It is unusual for both keyword arguments and the ``*expression`` syntax to be
575used in the same call, so in practice this confusion does not arise.
576
577If the syntax ``**expression`` appears in the function call, ``expression`` must
n578-evaluate to a (subclass of) dictionary, the contents of which are treated as
n714+evaluate to a mapping, the contents of which are treated as additional keyword
579-additional keyword arguments.  In the case of a keyword appearing in both
715+arguments.  In the case of a keyword appearing in both ``expression`` and as an
580-``expression`` and as an explicit keyword argument, a :exc:`TypeError` exception
716+explicit keyword argument, a :exc:`TypeError` exception is raised.
581-is raised.
582
583Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
584used as positional argument slots or as keyword argument names.  Formal
585parameters using the syntax ``(sublist)`` cannot be used as keyword argument
586names; the outermost sublist corresponds to a single unnamed argument slot, and
587the argument value is assigned to the sublist using the usual tuple assignment
588rules after all other parameter processing is done.
589
612      pair: built-in function; call
613      pair: method; call
614      pair: built-in method; call
615      object: built-in method
616      object: built-in function
617      object: method
618      object: function
619
n620-   The result is up to the interpreter; see the Python Library Reference (XXX
n755+   The result is up to the interpreter; see :ref:`built-in-funcs` for the
621-   reference: ../lib/built-in-funcs.html) for the descriptions of built-in
756+   descriptions of built-in functions and methods.
622-   functions and methods.
623
624a class object:
625   .. index::
626      object: class
627      pair: class object; call
628
629   A new instance of that class is returned.
630
651
652The power operator
653==================
654
655The power operator binds more tightly than unary operators on its left; it binds
656less tightly than unary operators on its right.  The syntax is:
657
658.. productionlist::
n659-   power: `primary` ["\*\*" `u_expr`]
n793+   power: `primary` ["**" `u_expr`]
660
661Thus, in an unparenthesized sequence of power and unary operators, the operators
662are evaluated from right to left (this does not constrain the evaluation order
n663-for the operands).
n797+for the operands): ``-1**2`` results in ``-1``.
664
665The power operator has the same semantics as the built-in :func:`pow` function,
666when called with two arguments: it yields its left argument raised to the power
667of its right argument.  The numeric arguments are first converted to a common
668type.  The result type is that of the arguments after coercion.
669
670With mixed operand types, the coercion rules for binary arithmetic operators
671apply. For int and long int operands, the result has the same type as the
677raised).
678
679Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
680Raising a negative number to a fractional power results in a :exc:`ValueError`.
681
682
683.. _unary:
684
n685-Unary arithmetic operations
n819+Unary arithmetic and bitwise operations
686-===========================
820+=======================================
687
688.. index::
689   triple: unary; arithmetic; operation
n690-   triple: unary; bit-wise; operation
n824+   triple: unary; bitwise; operation
691
n692-All unary arithmetic (and bit-wise) operations have the same priority:
n826+All unary arithmetic and bitwise operations have the same priority:
693
694.. productionlist::
n695-   u_expr: `power` \| "-" `u_expr` \| "+" `u_expr` \| "~" `u_expr`
n829+   u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
696
697.. index::
698   single: negation
699   single: minus
700
701The unary ``-`` (minus) operator yields the negation of its numeric argument.
702
703.. index:: single: plus
704
705The unary ``+`` (plus) operator yields its numeric argument unchanged.
706
707.. index:: single: inversion
708
n709-The unary ``~`` (invert) operator yields the bit-wise inversion of its plain or
n843+The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
710-long integer argument.  The bit-wise inversion of ``x`` is defined as
844+long integer argument.  The bitwise inversion of ``x`` is defined as
711``-(x+1)``.  It only applies to integral numbers.
712
713.. index:: exception: TypeError
714
715In all three cases, if the argument does not have the proper type, a
716:exc:`TypeError` exception is raised.
717
718
724.. index:: triple: binary; arithmetic; operation
725
726The binary arithmetic operations have the conventional priority levels.  Note
727that some of these operations also apply to certain non-numeric types.  Apart
728from the power operator, there are only two levels, one for multiplicative
729operators and one for additive operators:
730
731.. productionlist::
n732-   m_expr: `u_expr` \| `m_expr` "\*" `u_expr` \| `m_expr` "//" `u_expr` \| `m_expr` "/" `u_expr`
n866+   m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
733-         : \| `m_expr` "%" `u_expr`
867+         : | `m_expr` "%" `u_expr`
734-   a_expr: `m_expr` \| `a_expr` "+" `m_expr` \| `a_expr` "-" `m_expr`
868+   a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
735
736.. index:: single: multiplication
737
738The ``*`` (multiplication) operator yields the product of its arguments.  The
739arguments must either both be numbers, or one argument must be an integer (plain
740or long) and the other must be a sequence. In the former case, the numbers are
741converted to a common type and then multiplied together.  In the latter case,
742sequence repetition is performed; a negative repetition factor yields an empty
768connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y,
769x%y)``.  These identities don't hold for floating point numbers; there similar
770identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
771``floor(x/y) - 1`` [#]_.
772
773In addition to performing the modulo operation on numbers, the ``%`` operator is
774also overloaded by string and unicode objects to perform string formatting (also
775known as interpolation). The syntax for string formatting is described in the
n776-Python Library Reference (XXX reference: ../lib/typesseq-strings.html), section
n910+Python Library Reference, section :ref:`string-formatting`.
777-"Sequence Types".
778
779.. deprecated:: 2.3
780   The floor division operator, the modulo operator, and the :func:`divmod`
781   function are no longer defined for complex numbers.  Instead, convert to a
782   floating point number using the :func:`abs` function if appropriate.
783
784.. index:: single: addition
785
799Shifting operations
800===================
801
802.. index:: pair: shifting; operation
803
804The shifting operations have lower priority than the arithmetic operations:
805
806.. productionlist::
n807-   shift_expr: `a_expr` \| `shift_expr` ( "<<" \| ">>" ) `a_expr`
n940+   shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
808
809These operators accept plain or long integers as arguments.  The arguments are
810converted to a common type.  They shift the first argument to the left or right
811by the number of bits given by the second argument.
812
813.. index:: exception: ValueError
814
n815-A right shift by *n* bits is defined as division by ``pow(2,n)``.  A left shift
n948+A right shift by *n* bits is defined as division by ``pow(2, n)``.  A left shift
816-by *n* bits is defined as multiplication with ``pow(2,n)``; for plain integers
949+by *n* bits is defined as multiplication with ``pow(2, n)``.  Negative shift
817-there is no overflow check so in that case the operation drops bits and flips
818-the sign if the result is not less than ``pow(2,31)`` in absolute value.
819-Negative shift counts raise a :exc:`ValueError` exception.
950+counts raise a :exc:`ValueError` exception.
820
821
822.. _bitwise:
823
n824-Binary bit-wise operations
n955+Binary bitwise operations
825-==========================
956+=========================
826
n827-.. index:: triple: binary; bit-wise; operation
n958+.. index:: triple: binary; bitwise; operation
828
829Each of the three bitwise operations has a different priority level:
830
831.. productionlist::
n832-   and_expr: `shift_expr` \| `and_expr` "&" `shift_expr`
n963+   and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
833-   xor_expr: `and_expr` \| `xor_expr` "^" `and_expr`
964+   xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
834-   or_expr: `xor_expr` \| `or_expr` "\|" `xor_expr`
965+   or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
835
n836-.. index:: pair: bit-wise; and
n967+.. index:: pair: bitwise; and
837
838The ``&`` operator yields the bitwise AND of its arguments, which must be plain
839or long integers.  The arguments are converted to a common type.
840
841.. index::
n842-   pair: bit-wise; xor
n973+   pair: bitwise; xor
843   pair: exclusive; or
844
845The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
846must be plain or long integers.  The arguments are converted to a common type.
847
848.. index::
n849-   pair: bit-wise; or
n980+   pair: bitwise; or
850   pair: inclusive; or
851
852The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
853must be plain or long integers.  The arguments are converted to a common type.
854
855
856.. _comparisons:
n988+.. _is:
989+.. _isnot:
990+.. _in:
991+.. _notin:
857
858Comparisons
859===========
860
861.. index:: single: comparison
862
863.. index:: pair: C; language
864
865Unlike C, all comparison operations in Python have the same priority, which is
866lower than that of any arithmetic, shifting or bitwise operation.  Also unlike
867C, expressions like ``a < b < c`` have the interpretation that is conventional
868in mathematics:
869
870.. productionlist::
n871-   comparison: `or_expr` ( `comp_operator` `or_expr` )\*
n1006+   comparison: `or_expr` ( `comp_operator` `or_expr` )*
872-   comp_operator: "<" \| ">" \| "==" \| ">=" \| "<=" \| "<>" \| "!="
1007+   comp_operator: "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
873-                : \| "is" ["not"] \| ["not"] "in"
1008+                : | "is" ["not"] | ["not"] "in"
874
875Comparisons yield boolean values: ``True`` or ``False``.
876
877.. index:: pair: chaining; comparisons
878
879Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
880``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
881cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
882
n883-Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *opa*, *opb*, ...,
n1018+Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
884-*opy* are comparison operators, then *a opa b opb c* ...*y opy z* is equivalent
1019+*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
885-to *a opa b* :keyword:`and` *b opb c* :keyword:`and` ... *y opy z*, except that
1020+to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
886-each expression is evaluated at most once.
1021+evaluated at most once.
887
n888-Note that *a opa b opb c* doesn't imply any kind of comparison between *a* and
n1023+Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
889*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
890pretty).
891
892The forms ``<>`` and ``!=`` are equivalent; for consistency with C, ``!=`` is
893preferred; where ``!=`` is mentioned below ``<>`` is also accepted.  The ``<>``
894spelling is considered obsolescent.
895
896The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
907change.)
908
909Comparison of objects of the same type depends on the type:
910
911* Numbers are compared arithmetically.
912
913* Strings are compared lexicographically using the numeric equivalents (the
914  result of the built-in function :func:`ord`) of their characters.  Unicode and
n915-  8-bit strings are fully interoperable in this behavior.
n1050+  8-bit strings are fully interoperable in this behavior. [#]_
916
917* Tuples and lists are compared lexicographically using comparison of
918  corresponding elements.  This means that to compare equal, each element must
919  compare equal and the two sequences must be of the same type and have the same
920  length.
921
922  If not equal, the sequences are ordered the same as their first differing
923  elements.  For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
928  lists compare equal. [#]_ Outcomes other than equality are resolved
929  consistently, but are not otherwise defined. [#]_
930
931* Most other objects of builtin types compare unequal unless they are the same
932  object; the choice whether one object is considered smaller or larger than
933  another one is made arbitrarily but consistently within one execution of a
934  program.
935
n936-The operators :keyword:`in` and :keyword:`not in` test for set membership.  ``x
n1071+The operators :keyword:`in` and :keyword:`not in` test for collection
937-in s`` evaluates to true if *x* is a member of the set *s*, and false otherwise.
1072+membership.  ``x in s`` evaluates to true if *x* is a member of the collection
938-``x not in s`` returns the negation of ``x in s``. The set membership test has
1073+*s*, and false otherwise.  ``x not in s`` returns the negation of ``x in s``.
939-traditionally been bound to sequences; an object is a member of a set if the set
1074+The collection membership test has traditionally been bound to sequences; an
940-is a sequence and contains an element equal to that object.  However, it is
1075+object is a member of a collection if the collection is a sequence and contains
1076+an element equal to that object.  However, it make sense for many other object
941-possible for an object to support membership tests without being a sequence.  In
1077+types to support membership tests without being a sequence.  In particular,
942-particular, dictionaries support membership testing as a nicer way of spelling
1078+dictionaries (for keys) and sets support membership testing.
943-``key in dict``; other mapping types may follow suit.
944
945For the list and tuple types, ``x in y`` is true if and only if there exists an
946index *i* such that ``x == y[i]`` is true.
947
948For the Unicode and string types, ``x in y`` is true if and only if *x* is a
949substring of *y*.  An equivalent test is ``y.find(x) != -1``.  Note, *x* and *y*
950need not be the same type; consequently, ``u'ab' in 'abc'`` will return
951``True``. Empty strings are always considered to be a substring of any other
974
975.. index::
976   operator: is
977   operator: is not
978   pair: identity; test
979
980The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
981is y`` is true if and only if *x* and *y* are the same object.  ``x is not y``
n982-yields the inverse truth value.
n1117+yields the inverse truth value. [#]_
983
984
985.. _booleans:
n1121+.. _and:
1122+.. _or:
1123+.. _not:
986
987Boolean operations
988==================
989
n1128+.. index::
1129+   pair: Conditional; expression
990-.. index:: pair: Boolean; operation
1130+   pair: Boolean; operation
991
992Boolean operations have the lowest priority of all Python operations:
993
994.. productionlist::
n995-   expression: `or_test` [`if` `or_test` `else` `test`] \| `lambda_form`
n1135+   expression: `conditional_expression` | `lambda_form`
1136+   old_expression: `or_test` | `old_lambda_form`
1137+   conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
996-   or_test: `and_test` \| `or_test` "or" `and_test`
1138+   or_test: `and_test` | `or_test` "or" `and_test`
997-   and_test: `not_test` \| `and_test` "and" `not_test`
1139+   and_test: `not_test` | `and_test` "and" `not_test`
998-   not_test: `comparison` \| "not" `not_test`
1140+   not_test: `comparison` | "not" `not_test`
999
1000In the context of Boolean operations, and also when expressions are used by
1001control flow statements, the following values are interpreted as false:
1002``False``, ``None``, numeric zero of all types, and empty strings and containers
1003(including strings, tuples, lists, dictionaries, sets and frozensets).  All
n1004-other values are interpreted as true.
n1146+other values are interpreted as true.  (See the :meth:`~object.__nonzero__`
1147+special method for a way to change this.)
1005
1006.. index:: operator: not
1007
1008The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1009otherwise.
1010
1011The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is
1012true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated
1040
1041.. index::
1042   pair: lambda; expression
1043   pair: lambda; form
1044   pair: anonymous; function
1045
1046.. productionlist::
1047   lambda_form: "lambda" [`parameter_list`]: `expression`
n1191+   old_lambda_form: "lambda" [`parameter_list`]: `old_expression`
1048
1049Lambda forms (lambda expressions) have the same syntactic position as
1050expressions.  They are a shorthand to create anonymous functions; the expression
1051``lambda arguments: expression`` yields a function object.  The unnamed object
1052behaves like a function object defined with ::
1053
1054   def name(arguments):
1055       return expression
1063.. _exprlists:
1064
1065Expression lists
1066================
1067
1068.. index:: pair: expression; list
1069
1070.. productionlist::
n1071-   expression_list: `expression` ( "," `expression` )\* [","]
n1215+   expression_list: `expression` ( "," `expression` )* [","]
1072
1073.. index:: object: tuple
1074
1075An expression list containing at least one comma yields a tuple.  The length of
1076the tuple is the number of expressions in the list.  The expressions are
1077evaluated from left to right.
1078
1079.. index:: pair: trailing; comma
1097
1098In the following lines, expressions will be evaluated in the arithmetic order of
1099their suffixes::
1100
1101   expr1, expr2, expr3, expr4
1102   (expr1, expr2, expr3, expr4)
1103   {expr1: expr2, expr3: expr4}
1104   expr1 + expr2 * (expr3 - expr4)
n1105-   func(expr1expr2, *expr3, **expr4)
n1249+   expr1(expr2, expr3, *expr4, **expr5)
1106   expr3, expr4 = expr1, expr2
1107
1108
n1109-.. _summary:
n1253+.. _operator-summary:
1110
1111Summary
1112=======
1113
1114.. index:: pair: operator; precedence
1115
1116The following table summarizes the operator precedences in Python, from lowest
1117precedence (least binding) to highest precedence (most binding). Operators in
1118the same box have the same precedence.  Unless the syntax is explicitly given,
1119operators are binary.  Operators in the same box group left to right (except for
1120comparisons, including tests, which all have the same precedence and chain from
n1121-left to right --- see section :ref:`comparisons` -- and exponentiation, which
n1265+left to right --- see section :ref:`comparisons` --- and exponentiation, which
1122groups from right to left).
1123
1124+-----------------------------------------------+-------------------------------------+
1125| Operator                                      | Description                         |
1126+===============================================+=====================================+
1127| :keyword:`lambda`                             | Lambda expression                   |
1128+-----------------------------------------------+-------------------------------------+
1129| :keyword:`or`                                 | Boolean OR                          |
1130+-----------------------------------------------+-------------------------------------+
1131| :keyword:`and`                                | Boolean AND                         |
1132+-----------------------------------------------+-------------------------------------+
1133| :keyword:`not` *x*                            | Boolean NOT                         |
1134+-----------------------------------------------+-------------------------------------+
n1135-| :keyword:`in`, :keyword:`not` :keyword:`in`   | Membership tests                    |
n1279+| :keyword:`in`, :keyword:`not` :keyword:`in`,  | Comparisons, including membership   |
1136-+-----------------------------------------------+-------------------------------------+
1137-| :keyword:`is`, :keyword:`is not`              | Identity tests                      |
1280+| :keyword:`is`, :keyword:`is not`, ``<``,      | tests and identity tests,           |
1138-+-----------------------------------------------+-------------------------------------+
1139-| ``<``, ``<=``, ``>``, ``>=``, ``<>``, ``!=``, | Comparisons                         |
1281+| ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==``                                     |
1140-| ``==``                                        |                                     |
1141+-----------------------------------------------+-------------------------------------+
1142| ``|``                                         | Bitwise OR                          |
1143+-----------------------------------------------+-------------------------------------+
1144| ``^``                                         | Bitwise XOR                         |
1145+-----------------------------------------------+-------------------------------------+
1146| ``&``                                         | Bitwise AND                         |
1147+-----------------------------------------------+-------------------------------------+
1148| ``<<``, ``>>``                                | Shifts                              |
1149+-----------------------------------------------+-------------------------------------+
1150| ``+``, ``-``                                  | Addition and subtraction            |
1151+-----------------------------------------------+-------------------------------------+
n1152-| ``*``, ``/``, ``%``                           | Multiplication, division, remainder |
n1293+| ``*``, ``/``, ``//``, ``%``                   | Multiplication, division, remainder |
1153+-----------------------------------------------+-------------------------------------+
n1154-| ``+x``, ``-x``                                | Positive, negative                  |
n1295+| ``+x``, ``-x``, ``~x``                        | Positive, negative, bitwise NOT     |
1155+-----------------------------------------------+-------------------------------------+
n1156-| ``~x``                                        | Bitwise not                         |
1157-+-----------------------------------------------+-------------------------------------+
1158-| ``**``                                        | Exponentiation                      |
1297+| ``**``                                        | Exponentiation [#]_                 |
1159+-----------------------------------------------+-------------------------------------+
n1160-| ``x.attribute``                               | Attribute reference                 |
n1299+| ``x[index]``, ``x[index:index]``,             | Subscription, slicing,              |
1300+| ``x(arguments...)``, ``x.attribute``          | call, attribute reference           |
1161+-----------------------------------------------+-------------------------------------+
n1162-| ``x[index]``                                  | Subscription                        |
1163-+-----------------------------------------------+-------------------------------------+
1164-| ``x[index:index]``                            | Slicing                             |
1165-+-----------------------------------------------+-------------------------------------+
1166-| ``f(arguments...)``                           | Function call                       |
1167-+-----------------------------------------------+-------------------------------------+
1168-| ``(expressions...)``                          | Binding or tuple display            |
1302+| ``(expressions...)``,                         | Binding or tuple display,           |
1169-+-----------------------------------------------+-------------------------------------+
1170-| ``[expressions...]``                          | List display                        |
1303+| ``[expressions...]``,                         | list display,                       |
1171-+-----------------------------------------------+-------------------------------------+
1172-| ``{key:datum...}``                            | Dictionary display                  |
1304+| ``{key:datum...}``,                           | dictionary display,                 |
1173-+-----------------------------------------------+-------------------------------------+
1174-| ```expressions...```                        | String conversion                   |
1305+| ```expressions...```                          string conversion                   |
1175+-----------------------------------------------+-------------------------------------+
1176
1177.. rubric:: Footnotes
1178
n1179-.. [#] In Python 2.3, a list comprehension "leaks" the control variables of each
n1310+.. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control
1180-   ``for`` it contains into the containing scope.  However, this behavior is
1311+   variables of each ``for`` it contains into the containing scope.  However, this
1181-   deprecated, and relying on it will not work once this bug is fixed in a future
1312+   behavior is deprecated, and relying on it will not work in Python 3.0
1182-   release
1183
1184.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1185   true numerically due to roundoff.  For example, and assuming a platform on which
1186   a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1187   1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1188   1e100``, which is numerically exactly equal to ``1e100``.  Function :func:`fmod`
1189   in the :mod:`math` module returns a result whose sign matches the sign of the
1190   first argument instead, and so returns ``-1e-100`` in this case. Which approach
1191   is more appropriate depends on the application.
1192
1193.. [#] If x is very close to an exact integer multiple of y, it's possible for
1194   ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding.  In such
1195   cases, Python returns the latter result, in order to preserve that
1196   ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1197
n1328+.. [#] While comparisons between unicode strings make sense at the byte
1329+   level, they may be counter-intuitive to users. For example, the
1330+   strings ``u"\u00C7"`` and ``u"\u0043\u0327"`` compare differently,
1331+   even though they both represent the same unicode character (LATIN
1332+   CAPTITAL LETTER C WITH CEDILLA). To compare strings in a human
1333+   recognizable way, compare using :func:`unicodedata.normalize`.
1334+ 
1198.. [#] The implementation computes this efficiently, without constructing lists or
1199   sorting.
1200
1201.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
1202   value) lists, but this was very expensive for the common case of comparing for
1203   equality.  An even earlier version of Python compared dictionaries by identity
1204   only, but this caused surprises because people expected to be able to test a
1205   dictionary for emptiness by comparing it to ``{}``.
1206
t1344+.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
1345+   descriptors, you may notice seemingly unusual behaviour in certain uses of
1346+   the :keyword:`is` operator, like those involving comparisons between instance
1347+   methods, or constants.  Check their documentation for more info.
1348+ 
1349+.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1350+   bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op