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