Issue #7117: Update float formatting testcases to match those in py3k.
[python.git] / Doc / reference / expressions.rst
blobe06067030266a178e3fad8206365593ee25eab98
2 .. _expressions:
4 ***********
5 Expressions
6 ***********
8 .. index:: single: expression
10 This chapter explains the meaning of the elements of expressions in Python.
12 .. index:: single: BNF
14 **Syntax Notes:** In this and the following chapters, extended BNF notation will
15 be used to describe syntax, not lexical analysis.  When (one alternative of) a
16 syntax rule has the form
18 .. productionlist:: *
19    name: `othername`
21 .. index:: single: syntax
23 and no semantics are given, the semantics of this form of ``name`` are the same
24 as for ``othername``.
27 .. _conversions:
29 Arithmetic conversions
30 ======================
32 .. index:: pair: arithmetic; conversion
34 When a description of an arithmetic operator below uses the phrase "the numeric
35 arguments are converted to a common type," the arguments are coerced using the
36 coercion rules listed at  :ref:`coercion-rules`.  If both arguments are standard
37 numeric types, the following coercions are applied:
39 * If either argument is a complex number, the other is converted to complex;
41 * otherwise, if either argument is a floating point number, the other is
42   converted to floating point;
44 * otherwise, if either argument is a long integer, the other is converted to
45   long integer;
47 * otherwise, both must be plain integers and no conversion is necessary.
49 Some additional rules apply for certain operators (e.g., a string left argument
50 to the '%' operator). Extensions can define their own coercions.
53 .. _atoms:
55 Atoms
56 =====
58 .. index:: single: atom
60 Atoms are the most basic elements of expressions.  The simplest atoms are
61 identifiers or literals.  Forms enclosed in reverse quotes or in parentheses,
62 brackets or braces are also categorized syntactically as atoms.  The syntax for
63 atoms is:
65 .. productionlist::
66    atom: `identifier` | `literal` | `enclosure`
67    enclosure: `parenth_form` | `list_display`
68             : | `generator_expression` | `dict_display`
69             : | `string_conversion` | `yield_atom`
72 .. _atom-identifiers:
74 Identifiers (Names)
75 -------------------
77 .. index::
78    single: name
79    single: identifier
81 An identifier occurring as an atom is a name.  See section :ref:`identifiers`
82 for lexical definition and section :ref:`naming` for documentation of naming and
83 binding.
85 .. index:: exception: NameError
87 When the name is bound to an object, evaluation of the atom yields that object.
88 When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
89 exception.
91 .. index::
92    pair: name; mangling
93    pair: private; names
95 **Private name mangling:** When an identifier that textually occurs in a class
96 definition begins with two or more underscore characters and does not end in two
97 or more underscores, it is considered a :dfn:`private name` of that class.
98 Private names are transformed to a longer form before code is generated for
99 them.  The transformation inserts the class name in front of the name, with
100 leading underscores removed, and a single underscore inserted in front of the
101 class name.  For example, the identifier ``__spam`` occurring in a class named
102 ``Ham`` will be transformed to ``_Ham__spam``.  This transformation is
103 independent of the syntactical context in which the identifier is used.  If the
104 transformed name is extremely long (longer than 255 characters), implementation
105 defined truncation may happen.  If the class name consists only of underscores,
106 no transformation is done.
110 .. _atom-literals:
112 Literals
113 --------
115 .. index:: single: literal
117 Python supports string literals and various numeric literals:
119 .. productionlist::
120    literal: `stringliteral` | `integer` | `longinteger`
121           : | `floatnumber` | `imagnumber`
123 Evaluation of a literal yields an object of the given type (string, integer,
124 long integer, floating point number, complex number) with the given value.  The
125 value may be approximated in the case of floating point and imaginary (complex)
126 literals.  See section :ref:`literals` for details.
128 .. index::
129    triple: immutable; data; type
130    pair: immutable; object
132 All literals correspond to immutable data types, and hence the object's identity
133 is less important than its value.  Multiple evaluations of literals with the
134 same value (either the same occurrence in the program text or a different
135 occurrence) may obtain the same object or a different object with the same
136 value.
139 .. _parenthesized:
141 Parenthesized forms
142 -------------------
144 .. index:: single: parenthesized form
146 A parenthesized form is an optional expression list enclosed in parentheses:
148 .. productionlist::
149    parenth_form: "(" [`expression_list`] ")"
151 A parenthesized expression list yields whatever that expression list yields: if
152 the list contains at least one comma, it yields a tuple; otherwise, it yields
153 the single expression that makes up the expression list.
155 .. index:: pair: empty; tuple
157 An empty pair of parentheses yields an empty tuple object.  Since tuples are
158 immutable, the rules for literals apply (i.e., two occurrences of the empty
159 tuple may or may not yield the same object).
161 .. index::
162    single: comma
163    pair: tuple; display
165 Note that tuples are not formed by the parentheses, but rather by use of the
166 comma operator.  The exception is the empty tuple, for which parentheses *are*
167 required --- allowing unparenthesized "nothing" in expressions would cause
168 ambiguities and allow common typos to pass uncaught.
171 .. _lists:
173 List displays
174 -------------
176 .. index::
177    pair: list; display
178    pair: list; comprehensions
180 A list display is a possibly empty series of expressions enclosed in square
181 brackets:
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`]
191 .. index::
192    pair: list; comprehensions
193    object: list
194    pair: empty; list
196 A list display yields a new list object.  Its contents are specified by
197 providing either a list of expressions or a list comprehension.  When a
198 comma-separated list of expressions is supplied, its elements are evaluated from
199 left to right and placed into the list object in that order.  When a list
200 comprehension is supplied, it consists of a single expression followed by at
201 least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if`
202 clauses.  In this case, the elements of the new list are those that would be
203 produced by considering each of the :keyword:`for` or :keyword:`if` clauses a
204 block, nesting from left to right, and evaluating the expression to produce a
205 list element each time the innermost block is reached [#]_.
208 .. _genexpr:
210 Generator expressions
211 ---------------------
213 .. index:: pair: generator; expression
215 A generator expression is a compact generator notation in parentheses:
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`]
223 .. index:: object: generator
225 A generator expression yields a new generator object.  It consists of a single
226 expression 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
228 generator 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
230 evaluating the expression to yield a value that is reached the innermost block
231 for each iteration.
233 Variables used in the generator expression are evaluated lazily in a separate
234 scope when the :meth:`next` method is called for the generator object (in the
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
237 scope so that an error produced by it can be seen before any other possible
238 error in the code that handles the generator expression.  Subsequent
239 :keyword:`for` and :keyword:`if` clauses cannot be evaluated immediately since
240 they may depend on the previous :keyword:`for` loop.  For example:
241 ``(x*y for x in range(10) for y in bar(x))``.
243 The parentheses can be omitted on calls with only one argument. See section
244 :ref:`calls` for the detail.
247 .. _dict:
249 Dictionary displays
250 -------------------
252 .. index:: pair: dictionary; display
254 .. index::
255    single: key
256    single: datum
257    single: key/datum pair
259 A dictionary display is a possibly empty series of key/datum pairs enclosed in
260 curly braces:
262 .. productionlist::
263    dict_display: "{" [`key_datum_list`] "}"
264    key_datum_list: `key_datum` ("," `key_datum`)* [","]
265    key_datum: `expression` ":" `expression`
267 .. index:: object: dictionary
269 A dictionary display yields a new dictionary object.
271 The key/datum pairs are evaluated from left to right to define the entries of
272 the dictionary: each key object is used as a key into the dictionary to store
273 the corresponding datum.
275 .. index:: pair: immutable; object
277 Restrictions on the types of the key values are listed earlier in section
278 :ref:`types`.  (To summarize, the key type should be :term:`hashable`, which excludes
279 all mutable objects.)  Clashes between duplicate keys are not detected; the last
280 datum (textually rightmost in the display) stored for a given key value
281 prevails.
284 .. _string-conversions:
286 String conversions
287 ------------------
289 .. index::
290    pair: string; conversion
291    pair: reverse; quotes
292    pair: backward; quotes
293    single: back-quotes
295 A string conversion is an expression list enclosed in reverse (a.k.a. backward)
296 quotes:
298 .. productionlist::
299    string_conversion: "'" `expression_list` "'"
301 A string conversion evaluates the contained expression list and converts the
302 resulting object into a string according to rules specific to its type.
304 If the object is a string, a number, ``None``, or a tuple, list or dictionary
305 containing only objects whose type is one of these, the resulting string is a
306 valid Python expression which can be passed to the built-in function
307 :func:`eval` to yield an expression with the same value (or an approximation, if
308 floating point numbers are involved).
310 (In particular, converting a string adds quotes around it and converts "funny"
311 characters to escape sequences that are safe to print.)
313 .. index:: object: recursive
315 Recursive objects (for example, lists or dictionaries that contain a reference
316 to themselves, directly or indirectly) use ``...`` to indicate a recursive
317 reference, and the result cannot be passed to :func:`eval` to get an equal value
318 (:exc:`SyntaxError` will be raised instead).
320 .. index::
321    builtin: repr
322    builtin: str
324 The built-in function :func:`repr` performs exactly the same conversion in its
325 argument as enclosing it in parentheses and reverse quotes does.  The built-in
326 function :func:`str` performs a similar but more user-friendly conversion.
329 .. _yieldexpr:
331 Yield expressions
332 -----------------
334 .. index::
335    keyword: yield
336    pair: yield; expression
337    pair: generator; function
339 .. productionlist::
340    yield_atom: "(" `yield_expression` ")"
341    yield_expression: "yield" [`expression_list`]
343 .. versionadded:: 2.5
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.
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.
363 .. index:: single: coroutine
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.
371 .. index:: object: generator
373 The following generator's methods can be used to control the execution of a
374 generator function:
376 .. index:: exception: StopIteration
379 .. method:: generator.next()
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.
391 .. method:: generator.send(value)
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.
402 .. method:: generator.throw(type[, value[, traceback]])
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.
410 .. index:: exception: GeneratorExit
413 .. method:: generator.close()
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.
423 Here is a simple example that demonstrates the behavior of generators and
424 generator functions::
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.
451 .. seealso::
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.
458 .. _primaries:
460 Primaries
461 =========
463 .. index:: single: primary
465 Primaries represent the most tightly bound operations of the language. Their
466 syntax is:
468 .. productionlist::
469    primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
472 .. _attribute-references:
474 Attribute references
475 --------------------
477 .. index:: pair: attribute; reference
479 An attribute reference is a primary followed by a period and a name:
481 .. productionlist::
482    attributeref: `primary` "." `identifier`
484 .. index::
485    exception: AttributeError
486    object: module
487    object: list
489 The primary must evaluate to an object of a type that supports attribute
490 references, e.g., a module, list, or an instance.  This object is then asked to
491 produce the attribute whose name is the identifier.  If this attribute is not
492 available, the exception :exc:`AttributeError` is raised. Otherwise, the type
493 and value of the object produced is determined by the object.  Multiple
494 evaluations of the same attribute reference may yield different objects.
497 .. _subscriptions:
499 Subscriptions
500 -------------
502 .. index:: single: subscription
504 .. index::
505    object: sequence
506    object: mapping
507    object: string
508    object: tuple
509    object: list
510    object: dictionary
511    pair: sequence; item
513 A subscription selects an item of a sequence (string, tuple or list) or mapping
514 (dictionary) object:
516 .. productionlist::
517    subscription: `primary` "[" `expression_list` "]"
519 The primary must evaluate to an object of a sequence or mapping type.
521 If the primary is a mapping, the expression list must evaluate to an object
522 whose value is one of the keys of the mapping, and the subscription selects the
523 value in the mapping that corresponds to that key.  (The expression list is a
524 tuple except if it has exactly one item.)
526 If the primary is a sequence, the expression (list) must evaluate to a plain
527 integer.  If this value is negative, the length of the sequence is added to it
528 (so that, e.g., ``x[-1]`` selects the last item of ``x``.)  The resulting value
529 must be a nonnegative integer less than the number of items in the sequence, and
530 the subscription selects the item whose index is that value (counting from
531 zero).
533 .. index::
534    single: character
535    pair: string; item
537 A string's items are characters.  A character is not a separate data type but a
538 string of exactly one character.
541 .. _slicings:
543 Slicings
544 --------
546 .. index::
547    single: slicing
548    single: slice
550 .. index::
551    object: sequence
552    object: string
553    object: tuple
554    object: list
556 A slicing selects a range of items in a sequence object (e.g., a string, tuple
557 or list).  Slicings may be used as expressions or as targets in assignment or
558 :keyword:`del` statements.  The syntax for a slicing:
560 .. productionlist::
561    slicing: `simple_slicing` | `extended_slicing`
562    simple_slicing: `primary` "[" `short_slice` "]"
563    extended_slicing: `primary` "[" `slice_list` "]"
564    slice_list: `slice_item` ("," `slice_item`)* [","]
565    slice_item: `expression` | `proper_slice` | `ellipsis`
566    proper_slice: `short_slice` | `long_slice`
567    short_slice: [`lower_bound`] ":" [`upper_bound`]
568    long_slice: `short_slice` ":" [`stride`]
569    lower_bound: `expression`
570    upper_bound: `expression`
571    stride: `expression`
572    ellipsis: "..."
574 .. index:: pair: extended; slicing
576 There is ambiguity in the formal syntax here: anything that looks like an
577 expression list also looks like a slice list, so any subscription can be
578 interpreted as a slicing.  Rather than further complicating the syntax, this is
579 disambiguated by defining that in this case the interpretation as a subscription
580 takes priority over the interpretation as a slicing (this is the case if the
581 slice list contains no proper slice nor ellipses).  Similarly, when the slice
582 list has exactly one short slice and no trailing comma, the interpretation as a
583 simple slicing takes priority over that as an extended slicing.
585 The semantics for a simple slicing are as follows.  The primary must evaluate to
586 a sequence object.  The lower and upper bound expressions, if present, must
587 evaluate to plain integers; defaults are zero and the ``sys.maxint``,
588 respectively.  If either bound is negative, the sequence's length is added to
589 it.  The slicing now selects all items with index *k* such that ``i <= k < j``
590 where *i* and *j* are the specified lower and upper bounds.  This may be an
591 empty sequence.  It is not an error if *i* or *j* lie outside the range of valid
592 indexes (such items don't exist so they aren't selected).
594 .. index::
595    single: start (slice object attribute)
596    single: stop (slice object attribute)
597    single: step (slice object attribute)
599 The semantics for an extended slicing are as follows.  The primary must evaluate
600 to a mapping object, and it is indexed with a key that is constructed from the
601 slice list, as follows.  If the slice list contains at least one comma, the key
602 is a tuple containing the conversion of the slice items; otherwise, the
603 conversion of the lone slice item is the key.  The conversion of a slice item
604 that is an expression is that expression.  The conversion of an ellipsis slice
605 item is the built-in ``Ellipsis`` object.  The conversion of a proper slice is a
606 slice object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
607 :attr:`step` attributes are the values of the expressions given as lower bound,
608 upper bound and stride, respectively, substituting ``None`` for missing
609 expressions.
612 .. _calls:
614 Calls
615 -----
617 .. index:: single: call
619 .. index:: object: callable
621 A call calls a callable object (e.g., a function) with a possibly empty series
622 of arguments:
624 .. productionlist::
625    call: `primary` "(" [`argument_list` [","]
626        : | `expression` `genexpr_for`] ")"
627    argument_list: `positional_arguments` ["," `keyword_arguments`]
628                 :   ["," "*" `expression`] ["," `keyword_arguments`]
629                 :   ["," "**" `expression`]
630                 : | `keyword_arguments` ["," "*" `expression`]
631                 :   ["," "**" `expression`]
632                 : | "*" `expression` ["," "*" `expression`] ["," "**" `expression`]
633                 : | "**" `expression`
634    positional_arguments: `expression` ("," `expression`)*
635    keyword_arguments: `keyword_item` ("," `keyword_item`)*
636    keyword_item: `identifier` "=" `expression`
638 A trailing comma may be present after the positional and keyword arguments but
639 does not affect the semantics.
641 The primary must evaluate to a callable object (user-defined functions, built-in
642 functions, methods of built-in objects, class objects, methods of class
643 instances, and certain class instances themselves are callable; extensions may
644 define additional callable object types).  All argument expressions are
645 evaluated before the call is attempted.  Please refer to section :ref:`function`
646 for the syntax of formal parameter lists.
648 If keyword arguments are present, they are first converted to positional
649 arguments, as follows.  First, a list of unfilled slots is created for the
650 formal parameters.  If there are N positional arguments, they are placed in the
651 first N slots.  Next, for each keyword argument, the identifier is used to
652 determine the corresponding slot (if the identifier is the same as the first
653 formal parameter name, the first slot is used, and so on).  If the slot is
654 already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
655 the argument is placed in the slot, filling it (even if the expression is
656 ``None``, it fills the slot).  When all arguments have been processed, the slots
657 that are still unfilled are filled with the corresponding default value from the
658 function definition.  (Default values are calculated, once, when the function is
659 defined; thus, a mutable object such as a list or dictionary used as default
660 value will be shared by all calls that don't specify an argument value for the
661 corresponding slot; this should usually be avoided.)  If there are any unfilled
662 slots for which no default value is specified, a :exc:`TypeError` exception is
663 raised.  Otherwise, the list of filled slots is used as the argument list for
664 the call.
666 .. impl-detail::
668    An implementation may provide built-in functions whose positional parameters
669    do not have names, even if they are 'named' for the purpose of documentation,
670    and which therefore cannot be supplied by keyword.  In CPython, this is the
671    case for functions implemented in C that use :cfunc:`PyArg_ParseTuple` to
672    parse their arguments.
674 If there are more positional arguments than there are formal parameter slots, a
675 :exc:`TypeError` exception is raised, unless a formal parameter using the syntax
676 ``*identifier`` is present; in this case, that formal parameter receives a tuple
677 containing the excess positional arguments (or an empty tuple if there were no
678 excess positional arguments).
680 If any keyword argument does not correspond to a formal parameter name, a
681 :exc:`TypeError` exception is raised, unless a formal parameter using the syntax
682 ``**identifier`` is present; in this case, that formal parameter receives a
683 dictionary containing the excess keyword arguments (using the keywords as keys
684 and the argument values as corresponding values), or a (new) empty dictionary if
685 there were no excess keyword arguments.
687 If the syntax ``*expression`` appears in the function call, ``expression`` must
688 evaluate to a sequence.  Elements from this sequence are treated as if they were
689 additional positional arguments; if there are positional arguments *x1*,...,
690 *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this is
691 equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*, ...,
692 *yM*.
694 A consequence of this is that although the ``*expression`` syntax may appear
695 *after* some keyword arguments, it is processed *before* the keyword arguments
696 (and the ``**expression`` argument, if any -- see below).  So::
698    >>> def f(a, b):
699    ...  print a, b
700    ...
701    >>> f(b=1, *(2,))
702    2 1
703    >>> f(a=1, *(2,))
704    Traceback (most recent call last):
705      File "<stdin>", line 1, in ?
706    TypeError: f() got multiple values for keyword argument 'a'
707    >>> f(1, *(2,))
708    1 2
710 It is unusual for both keyword arguments and the ``*expression`` syntax to be
711 used in the same call, so in practice this confusion does not arise.
713 If the syntax ``**expression`` appears in the function call, ``expression`` must
714 evaluate to a mapping, the contents of which are treated as additional keyword
715 arguments.  In the case of a keyword appearing in both ``expression`` and as an
716 explicit keyword argument, a :exc:`TypeError` exception is raised.
718 Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
719 used as positional argument slots or as keyword argument names.  Formal
720 parameters using the syntax ``(sublist)`` cannot be used as keyword argument
721 names; the outermost sublist corresponds to a single unnamed argument slot, and
722 the argument value is assigned to the sublist using the usual tuple assignment
723 rules after all other parameter processing is done.
725 A call always returns some value, possibly ``None``, unless it raises an
726 exception.  How this value is computed depends on the type of the callable
727 object.
729 If it is---
731 a user-defined function:
732    .. index::
733       pair: function; call
734       triple: user-defined; function; call
735       object: user-defined function
736       object: function
738    The code block for the function is executed, passing it the argument list.  The
739    first thing the code block will do is bind the formal parameters to the
740    arguments; this is described in section :ref:`function`.  When the code block
741    executes a :keyword:`return` statement, this specifies the return value of the
742    function call.
744 a built-in function or method:
745    .. index::
746       pair: function; call
747       pair: built-in function; call
748       pair: method; call
749       pair: built-in method; call
750       object: built-in method
751       object: built-in function
752       object: method
753       object: function
755    The result is up to the interpreter; see :ref:`built-in-funcs` for the
756    descriptions of built-in functions and methods.
758 a class object:
759    .. index::
760       object: class
761       pair: class object; call
763    A new instance of that class is returned.
765 a class instance method:
766    .. index::
767       object: class instance
768       object: instance
769       pair: class instance; call
771    The corresponding user-defined function is called, with an argument list that is
772    one longer than the argument list of the call: the instance becomes the first
773    argument.
775 a class instance:
776    .. index::
777       pair: instance; call
778       single: __call__() (object method)
780    The class must define a :meth:`__call__` method; the effect is then the same as
781    if that method was called.
784 .. _power:
786 The power operator
787 ==================
789 The power operator binds more tightly than unary operators on its left; it binds
790 less tightly than unary operators on its right.  The syntax is:
792 .. productionlist::
793    power: `primary` ["**" `u_expr`]
795 Thus, in an unparenthesized sequence of power and unary operators, the operators
796 are evaluated from right to left (this does not constrain the evaluation order
797 for the operands): ``-1**2`` results in ``-1``.
799 The power operator has the same semantics as the built-in :func:`pow` function,
800 when called with two arguments: it yields its left argument raised to the power
801 of its right argument.  The numeric arguments are first converted to a common
802 type.  The result type is that of the arguments after coercion.
804 With mixed operand types, the coercion rules for binary arithmetic operators
805 apply. For int and long int operands, the result has the same type as the
806 operands (after coercion) unless the second argument is negative; in that case,
807 all arguments are converted to float and a float result is delivered. For
808 example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last
809 feature was added in Python 2.2. In Python 2.1 and before, if both arguments
810 were of integer types and the second argument was negative, an exception was
811 raised).
813 Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
814 Raising a negative number to a fractional power results in a :exc:`ValueError`.
817 .. _unary:
819 Unary arithmetic and bitwise operations
820 =======================================
822 .. index::
823    triple: unary; arithmetic; operation
824    triple: unary; bitwise; operation
826 All unary arithmetic and bitwise operations have the same priority:
828 .. productionlist::
829    u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
831 .. index::
832    single: negation
833    single: minus
835 The unary ``-`` (minus) operator yields the negation of its numeric argument.
837 .. index:: single: plus
839 The unary ``+`` (plus) operator yields its numeric argument unchanged.
841 .. index:: single: inversion
843 The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
844 long integer argument.  The bitwise inversion of ``x`` is defined as
845 ``-(x+1)``.  It only applies to integral numbers.
847 .. index:: exception: TypeError
849 In all three cases, if the argument does not have the proper type, a
850 :exc:`TypeError` exception is raised.
853 .. _binary:
855 Binary arithmetic operations
856 ============================
858 .. index:: triple: binary; arithmetic; operation
860 The binary arithmetic operations have the conventional priority levels.  Note
861 that some of these operations also apply to certain non-numeric types.  Apart
862 from the power operator, there are only two levels, one for multiplicative
863 operators and one for additive operators:
865 .. productionlist::
866    m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
867          : | `m_expr` "%" `u_expr`
868    a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
870 .. index:: single: multiplication
872 The ``*`` (multiplication) operator yields the product of its arguments.  The
873 arguments must either both be numbers, or one argument must be an integer (plain
874 or long) and the other must be a sequence. In the former case, the numbers are
875 converted to a common type and then multiplied together.  In the latter case,
876 sequence repetition is performed; a negative repetition factor yields an empty
877 sequence.
879 .. index::
880    exception: ZeroDivisionError
881    single: division
883 The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
884 their arguments.  The numeric arguments are first converted to a common type.
885 Plain or long integer division yields an integer of the same type; the result is
886 that of mathematical division with the 'floor' function applied to the result.
887 Division by zero raises the :exc:`ZeroDivisionError` exception.
889 .. index:: single: modulo
891 The ``%`` (modulo) operator yields the remainder from the division of the first
892 argument by the second.  The numeric arguments are first converted to a common
893 type.  A zero right argument raises the :exc:`ZeroDivisionError` exception.  The
894 arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
895 (since ``3.14`` equals ``4*0.7 + 0.34``.)  The modulo operator always yields a
896 result with the same sign as its second operand (or zero); the absolute value of
897 the result is strictly smaller than the absolute value of the second operand
898 [#]_.
900 The integer division and modulo operators are connected by the following
901 identity: ``x == (x/y)*y + (x%y)``.  Integer division and modulo are also
902 connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y,
903 x%y)``.  These identities don't hold for floating point numbers; there similar
904 identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
905 ``floor(x/y) - 1`` [#]_.
907 In addition to performing the modulo operation on numbers, the ``%`` operator is
908 also overloaded by string and unicode objects to perform string formatting (also
909 known as interpolation). The syntax for string formatting is described in the
910 Python Library Reference, section :ref:`string-formatting`.
912 .. deprecated:: 2.3
913    The floor division operator, the modulo operator, and the :func:`divmod`
914    function are no longer defined for complex numbers.  Instead, convert to a
915    floating point number using the :func:`abs` function if appropriate.
917 .. index:: single: addition
919 The ``+`` (addition) operator yields the sum of its arguments. The arguments
920 must either both be numbers or both sequences of the same type.  In the former
921 case, the numbers are converted to a common type and then added together.  In
922 the latter case, the sequences are concatenated.
924 .. index:: single: subtraction
926 The ``-`` (subtraction) operator yields the difference of its arguments.  The
927 numeric arguments are first converted to a common type.
930 .. _shifting:
932 Shifting operations
933 ===================
935 .. index:: pair: shifting; operation
937 The shifting operations have lower priority than the arithmetic operations:
939 .. productionlist::
940    shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
942 These operators accept plain or long integers as arguments.  The arguments are
943 converted to a common type.  They shift the first argument to the left or right
944 by the number of bits given by the second argument.
946 .. index:: exception: ValueError
948 A right shift by *n* bits is defined as division by ``pow(2, n)``.  A left shift
949 by *n* bits is defined as multiplication with ``pow(2, n)``.  Negative shift
950 counts raise a :exc:`ValueError` exception.
953 .. _bitwise:
955 Binary bitwise operations
956 =========================
958 .. index:: triple: binary; bitwise; operation
960 Each of the three bitwise operations has a different priority level:
962 .. productionlist::
963    and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
964    xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
965    or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
967 .. index:: pair: bitwise; and
969 The ``&`` operator yields the bitwise AND of its arguments, which must be plain
970 or long integers.  The arguments are converted to a common type.
972 .. index::
973    pair: bitwise; xor
974    pair: exclusive; or
976 The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
977 must be plain or long integers.  The arguments are converted to a common type.
979 .. index::
980    pair: bitwise; or
981    pair: inclusive; or
983 The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
984 must be plain or long integers.  The arguments are converted to a common type.
987 .. _comparisons:
988 .. _is:
989 .. _isnot:
990 .. _in:
991 .. _notin:
993 Comparisons
994 ===========
996 .. index:: single: comparison
998 .. index:: pair: C; language
1000 Unlike C, all comparison operations in Python have the same priority, which is
1001 lower than that of any arithmetic, shifting or bitwise operation.  Also unlike
1002 C, expressions like ``a < b < c`` have the interpretation that is conventional
1003 in mathematics:
1005 .. productionlist::
1006    comparison: `or_expr` ( `comp_operator` `or_expr` )*
1007    comp_operator: "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
1008                 : | "is" ["not"] | ["not"] "in"
1010 Comparisons yield boolean values: ``True`` or ``False``.
1012 .. index:: pair: chaining; comparisons
1014 Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1015 ``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1016 cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1018 Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1019 *opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1020 to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1021 evaluated at most once.
1023 Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
1024 *c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1025 pretty).
1027 The forms ``<>`` and ``!=`` are equivalent; for consistency with C, ``!=`` is
1028 preferred; where ``!=`` is mentioned below ``<>`` is also accepted.  The ``<>``
1029 spelling is considered obsolescent.
1031 The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1032 values of two objects.  The objects need not have the same type. If both are
1033 numbers, they are converted to a common type.  Otherwise, objects of different
1034 types *always* compare unequal, and are ordered consistently but arbitrarily.
1035 You can control comparison behavior of objects of non-built-in types by defining
1036 a ``__cmp__`` method or rich comparison methods like ``__gt__``, described in
1037 section :ref:`specialnames`.
1039 (This unusual definition of comparison was used to simplify the definition of
1040 operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
1041 In the future, the comparison rules for objects of different types are likely to
1042 change.)
1044 Comparison of objects of the same type depends on the type:
1046 * Numbers are compared arithmetically.
1048 * Strings are compared lexicographically using the numeric equivalents (the
1049   result of the built-in function :func:`ord`) of their characters.  Unicode and
1050   8-bit strings are fully interoperable in this behavior. [#]_
1052 * Tuples and lists are compared lexicographically using comparison of
1053   corresponding elements.  This means that to compare equal, each element must
1054   compare equal and the two sequences must be of the same type and have the same
1055   length.
1057   If not equal, the sequences are ordered the same as their first differing
1058   elements.  For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
1059   ``cmp(x,y)``.  If the corresponding element does not exist, the shorter sequence
1060   is ordered first (for example, ``[1,2] < [1,2,3]``).
1062 * Mappings (dictionaries) compare equal if and only if their sorted (key, value)
1063   lists compare equal. [#]_ Outcomes other than equality are resolved
1064   consistently, but are not otherwise defined. [#]_
1066 * Most other objects of built-in types compare unequal unless they are the same
1067   object; the choice whether one object is considered smaller or larger than
1068   another one is made arbitrarily but consistently within one execution of a
1069   program.
1071 .. _membership-test-details:
1073 The operators :keyword:`in` and :keyword:`not in` test for collection
1074 membership.  ``x in s`` evaluates to true if *x* is a member of the collection
1075 *s*, and false otherwise.  ``x not in s`` returns the negation of ``x in s``.
1076 The collection membership test has traditionally been bound to sequences; an
1077 object is a member of a collection if the collection is a sequence and contains
1078 an element equal to that object.  However, it make sense for many other object
1079 types to support membership tests without being a sequence.  In particular,
1080 dictionaries (for keys) and sets support membership testing.
1082 For the list and tuple types, ``x in y`` is true if and only if there exists an
1083 index *i* such that ``x == y[i]`` is true.
1085 For the Unicode and string types, ``x in y`` is true if and only if *x* is a
1086 substring of *y*.  An equivalent test is ``y.find(x) != -1``.  Note, *x* and *y*
1087 need not be the same type; consequently, ``u'ab' in 'abc'`` will return
1088 ``True``. Empty strings are always considered to be a substring of any other
1089 string, so ``"" in "abc"`` will return ``True``.
1091 .. versionchanged:: 2.3
1092    Previously, *x* was required to be a string of length ``1``.
1094 For user-defined classes which define the :meth:`__contains__` method, ``x in
1095 y`` is true if and only if ``y.__contains__(x)`` is true.
1097 For user-defined classes which do not define :meth:`__contains__` but do define
1098 :meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1099 produced while iterating over ``y``.  If an exception is raised during the
1100 iteration, it is as if :keyword:`in` raised that exception.
1102 Lastly, the old-style iteration protocol is tried: if a class defines
1103 :meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1104 integer index *i* such that ``x == y[i]``, and all lower integer indices do not
1105 raise :exc:`IndexError` exception. (If any other exception is raised, it is as
1106 if :keyword:`in` raised that exception).
1108 .. index::
1109    operator: in
1110    operator: not in
1111    pair: membership; test
1112    object: sequence
1114 The operator :keyword:`not in` is defined to have the inverse true value of
1115 :keyword:`in`.
1117 .. index::
1118    operator: is
1119    operator: is not
1120    pair: identity; test
1122 The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1123 is y`` is true if and only if *x* and *y* are the same object.  ``x is not y``
1124 yields the inverse truth value. [#]_
1127 .. _booleans:
1128 .. _and:
1129 .. _or:
1130 .. _not:
1132 Boolean operations
1133 ==================
1135 .. index::
1136    pair: Conditional; expression
1137    pair: Boolean; operation
1139 Boolean operations have the lowest priority of all Python operations:
1141 .. productionlist::
1142    expression: `conditional_expression` | `lambda_form`
1143    old_expression: `or_test` | `old_lambda_form`
1144    conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1145    or_test: `and_test` | `or_test` "or" `and_test`
1146    and_test: `not_test` | `and_test` "and" `not_test`
1147    not_test: `comparison` | "not" `not_test`
1149 In the context of Boolean operations, and also when expressions are used by
1150 control flow statements, the following values are interpreted as false:
1151 ``False``, ``None``, numeric zero of all types, and empty strings and containers
1152 (including strings, tuples, lists, dictionaries, sets and frozensets).  All
1153 other values are interpreted as true.  (See the :meth:`~object.__nonzero__`
1154 special method for a way to change this.)
1156 .. index:: operator: not
1158 The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1159 otherwise.
1161 The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is
1162 true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated
1163 and its value is returned.
1165 .. versionadded:: 2.5
1167 .. index:: operator: and
1169 The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1170 returned; otherwise, *y* is evaluated and the resulting value is returned.
1172 .. index:: operator: or
1174 The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1175 returned; otherwise, *y* is evaluated and the resulting value is returned.
1177 (Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1178 they return to ``False`` and ``True``, but rather return the last evaluated
1179 argument. This is sometimes useful, e.g., if ``s`` is a string that should be
1180 replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1181 the desired value.  Because :keyword:`not` has to invent a value anyway, it does
1182 not bother to return a value of the same type as its argument, so e.g., ``not
1183 'foo'`` yields ``False``, not ``''``.)
1186 .. _lambdas:
1187 .. _lambda:
1189 Lambdas
1190 =======
1192 .. index::
1193    pair: lambda; expression
1194    pair: lambda; form
1195    pair: anonymous; function
1197 .. productionlist::
1198    lambda_form: "lambda" [`parameter_list`]: `expression`
1199    old_lambda_form: "lambda" [`parameter_list`]: `old_expression`
1201 Lambda forms (lambda expressions) have the same syntactic position as
1202 expressions.  They are a shorthand to create anonymous functions; the expression
1203 ``lambda arguments: expression`` yields a function object.  The unnamed object
1204 behaves like a function object defined with ::
1206    def name(arguments):
1207        return expression
1209 See section :ref:`function` for the syntax of parameter lists.  Note that
1210 functions created with lambda forms cannot contain statements.
1213 .. _exprlists:
1215 Expression lists
1216 ================
1218 .. index:: pair: expression; list
1220 .. productionlist::
1221    expression_list: `expression` ( "," `expression` )* [","]
1223 .. index:: object: tuple
1225 An expression list containing at least one comma yields a tuple.  The length of
1226 the tuple is the number of expressions in the list.  The expressions are
1227 evaluated from left to right.
1229 .. index:: pair: trailing; comma
1231 The trailing comma is required only to create a single tuple (a.k.a. a
1232 *singleton*); it is optional in all other cases.  A single expression without a
1233 trailing comma doesn't create a tuple, but rather yields the value of that
1234 expression. (To create an empty tuple, use an empty pair of parentheses:
1235 ``()``.)
1238 .. _evalorder:
1240 Evaluation order
1241 ================
1243 .. index:: pair: evaluation; order
1245 Python evaluates expressions from left to right. Notice that while evaluating an
1246 assignment, the right-hand side is evaluated before the left-hand side.
1248 In the following lines, expressions will be evaluated in the arithmetic order of
1249 their suffixes::
1251    expr1, expr2, expr3, expr4
1252    (expr1, expr2, expr3, expr4)
1253    {expr1: expr2, expr3: expr4}
1254    expr1 + expr2 * (expr3 - expr4)
1255    expr1(expr2, expr3, *expr4, **expr5)
1256    expr3, expr4 = expr1, expr2
1259 .. _operator-summary:
1261 Summary
1262 =======
1264 .. index:: pair: operator; precedence
1266 The following table summarizes the operator precedences in Python, from lowest
1267 precedence (least binding) to highest precedence (most binding). Operators in
1268 the same box have the same precedence.  Unless the syntax is explicitly given,
1269 operators are binary.  Operators in the same box group left to right (except for
1270 comparisons, including tests, which all have the same precedence and chain from
1271 left to right --- see section :ref:`comparisons` --- and exponentiation, which
1272 groups from right to left).
1274 +-----------------------------------------------+-------------------------------------+
1275 | Operator                                      | Description                         |
1276 +===============================================+=====================================+
1277 | :keyword:`lambda`                             | Lambda expression                   |
1278 +-----------------------------------------------+-------------------------------------+
1279 | :keyword:`or`                                 | Boolean OR                          |
1280 +-----------------------------------------------+-------------------------------------+
1281 | :keyword:`and`                                | Boolean AND                         |
1282 +-----------------------------------------------+-------------------------------------+
1283 | :keyword:`not` *x*                            | Boolean NOT                         |
1284 +-----------------------------------------------+-------------------------------------+
1285 | :keyword:`in`, :keyword:`not` :keyword:`in`,  | Comparisons, including membership   |
1286 | :keyword:`is`, :keyword:`is not`, ``<``,      | tests and identity tests,           |
1287 | ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==`` |                                     |
1288 +-----------------------------------------------+-------------------------------------+
1289 | ``|``                                         | Bitwise OR                          |
1290 +-----------------------------------------------+-------------------------------------+
1291 | ``^``                                         | Bitwise XOR                         |
1292 +-----------------------------------------------+-------------------------------------+
1293 | ``&``                                         | Bitwise AND                         |
1294 +-----------------------------------------------+-------------------------------------+
1295 | ``<<``, ``>>``                                | Shifts                              |
1296 +-----------------------------------------------+-------------------------------------+
1297 | ``+``, ``-``                                  | Addition and subtraction            |
1298 +-----------------------------------------------+-------------------------------------+
1299 | ``*``, ``/``, ``//``, ``%``                   | Multiplication, division, remainder |
1300 +-----------------------------------------------+-------------------------------------+
1301 | ``+x``, ``-x``, ``~x``                        | Positive, negative, bitwise NOT     |
1302 +-----------------------------------------------+-------------------------------------+
1303 | ``**``                                        | Exponentiation [#]_                 |
1304 +-----------------------------------------------+-------------------------------------+
1305 | ``x[index]``, ``x[index:index]``,             | Subscription, slicing,              |
1306 | ``x(arguments...)``, ``x.attribute``          | call, attribute reference           |
1307 +-----------------------------------------------+-------------------------------------+
1308 | ``(expressions...)``,                         | Binding or tuple display,           |
1309 | ``[expressions...]``,                         | list display,                       |
1310 | ``{key:datum...}``,                           | dictionary display,                 |
1311 | ```expressions...```                          | string conversion                   |
1312 +-----------------------------------------------+-------------------------------------+
1314 .. rubric:: Footnotes
1316 .. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control
1317    variables of each ``for`` it contains into the containing scope.  However, this
1318    behavior is deprecated, and relying on it will not work in Python 3.0
1320 .. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1321    true numerically due to roundoff.  For example, and assuming a platform on which
1322    a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1323    1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1324    1e100``, which is numerically exactly equal to ``1e100``.  Function :func:`fmod`
1325    in the :mod:`math` module returns a result whose sign matches the sign of the
1326    first argument instead, and so returns ``-1e-100`` in this case. Which approach
1327    is more appropriate depends on the application.
1329 .. [#] If x is very close to an exact integer multiple of y, it's possible for
1330    ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding.  In such
1331    cases, Python returns the latter result, in order to preserve that
1332    ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1334 .. [#] While comparisons between unicode strings make sense at the byte
1335    level, they may be counter-intuitive to users. For example, the
1336    strings ``u"\u00C7"`` and ``u"\u0043\u0327"`` compare differently,
1337    even though they both represent the same unicode character (LATIN
1338    CAPTITAL LETTER C WITH CEDILLA). To compare strings in a human
1339    recognizable way, compare using :func:`unicodedata.normalize`.
1341 .. [#] The implementation computes this efficiently, without constructing lists or
1342    sorting.
1344 .. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
1345    value) lists, but this was very expensive for the common case of comparing for
1346    equality.  An even earlier version of Python compared dictionaries by identity
1347    only, but this caused surprises because people expected to be able to test a
1348    dictionary for emptiness by comparing it to ``{}``.
1350 .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
1351    descriptors, you may notice seemingly unusual behaviour in certain uses of
1352    the :keyword:`is` operator, like those involving comparisons between instance
1353    methods, or constants.  Check their documentation for more info.
1355 .. [#] The power operator ``**`` binds less tightly than an arithmetic or
1356    bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.