blob: 6481894a4d1d375da85a5636cfe134d3ed964fc6 [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
Georg Brandl8e67ef52008-03-03 21:31:50 +0000233Variables used in the generator expression are evaluated lazily in a separate
234scope when the :meth:`next` method is called for the generator object (in the
235same fashion as for normal generators). However, the :keyword:`in` expression
236of the leftmost :keyword:`for` clause is immediately evaluated in the current
237scope so that an error produced by it can be seen before any other possible
238error in the code that handles the generator expression. Subsequent
239:keyword:`for` and :keyword:`if` clauses cannot be evaluated immediately since
240they may depend on the previous :keyword:`for` loop. For example:
241``(x*y for x in range(10) for y in bar(x))``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000242
243The parentheses can be omitted on calls with only one argument. See section
244:ref:`calls` for the detail.
245
246
247.. _dict:
248
249Dictionary displays
250-------------------
251
252.. index:: pair: dictionary; display
253
254.. index::
255 single: key
256 single: datum
257 single: key/datum pair
258
259A dictionary display is a possibly empty series of key/datum pairs enclosed in
260curly braces:
261
262.. productionlist::
263 dict_display: "{" [`key_datum_list`] "}"
264 key_datum_list: `key_datum` ("," `key_datum`)* [","]
265 key_datum: `expression` ":" `expression`
266
267.. index:: object: dictionary
268
269A dictionary display yields a new dictionary object.
270
271The key/datum pairs are evaluated from left to right to define the entries of
272the dictionary: each key object is used as a key into the dictionary to store
273the corresponding datum.
274
275.. index:: pair: immutable; object
276
277Restrictions on the types of the key values are listed earlier in section
Georg Brandl7c3e79f2007-11-02 20:06:17 +0000278:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279all mutable objects.) Clashes between duplicate keys are not detected; the last
280datum (textually rightmost in the display) stored for a given key value
281prevails.
282
283
284.. _string-conversions:
285
286String conversions
287------------------
288
289.. index::
290 pair: string; conversion
291 pair: reverse; quotes
292 pair: backward; quotes
293 single: back-quotes
294
295A string conversion is an expression list enclosed in reverse (a.k.a. backward)
296quotes:
297
298.. productionlist::
299 string_conversion: "'" `expression_list` "'"
300
301A string conversion evaluates the contained expression list and converts the
302resulting object into a string according to rules specific to its type.
303
304If the object is a string, a number, ``None``, or a tuple, list or dictionary
305containing only objects whose type is one of these, the resulting string is a
306valid 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
308floating point numbers are involved).
309
310(In particular, converting a string adds quotes around it and converts "funny"
311characters to escape sequences that are safe to print.)
312
313.. index:: object: recursive
314
315Recursive objects (for example, lists or dictionaries that contain a reference
316to themselves, directly or indirectly) use ``...`` to indicate a recursive
317reference, and the result cannot be passed to :func:`eval` to get an equal value
318(:exc:`SyntaxError` will be raised instead).
319
320.. index::
321 builtin: repr
322 builtin: str
323
324The built-in function :func:`repr` performs exactly the same conversion in its
325argument as enclosing it in parentheses and reverse quotes does. The built-in
326function :func:`str` performs a similar but more user-friendly conversion.
327
328
329.. _yieldexpr:
330
331Yield expressions
332-----------------
333
334.. index::
335 keyword: yield
336 pair: yield; expression
337 pair: generator; function
338
339.. productionlist::
340 yield_atom: "(" `yield_expression` ")"
341 yield_expression: "yield" [`expression_list`]
342
343.. versionadded:: 2.5
344
345The :keyword:`yield` expression is only used when defining a generator function,
346and 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
348definition to create a generator function instead of a normal function.
349
350When a generator function is called, it returns an iterator known as a
351generator. That generator then controls the execution of a generator function.
352The execution starts when one of the generator's methods is called. At that
353time, the execution proceeds to the first :keyword:`yield` expression, where it
354is suspended again, returning the value of :token:`expression_list` to
355generator's caller. By suspended we mean that all local state is retained,
356including the current bindings of local variables, the instruction pointer, and
357the internal evaluation stack. When the execution is resumed by calling one of
358the 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
361the execution.
362
363.. index:: single: coroutine
364
365All of this makes generator functions quite similar to coroutines; they yield
366multiple times, they have more than one entry point and their execution can be
367suspended. The only difference is that a generator function cannot control
368where should the execution continue after it yields; the control is always
369transfered to the generator's caller.
370
371.. index:: object: generator
372
373The following generator's methods can be used to control the execution of a
374generator function:
375
376.. index:: exception: StopIteration
377
378
379.. method:: generator.next()
380
381 Starts the execution of a generator function or resumes it at the last executed
382 :keyword:`yield` expression. When a generator function is resumed with a
383 :meth:`next` method, the current :keyword:`yield` expression always evaluates to
384 :const:`None`. The execution then continues to the next :keyword:`yield`
385 expression, where the generator is suspended again, and the value of the
386 :token:`expression_list` is returned to :meth:`next`'s caller. If the generator
387 exits without yielding another value, a :exc:`StopIteration` exception is
388 raised.
389
390
391.. method:: generator.send(value)
392
393 Resumes the execution and "sends" a value into the generator function. The
394 ``value`` argument becomes the result of the current :keyword:`yield`
395 expression. The :meth:`send` method returns the next value yielded by the
396 generator, or raises :exc:`StopIteration` if the generator exits without
397 yielding another value. When :meth:`send` is called to start the generator, it
398 must be called with :const:`None` as the argument, because there is no
Georg Brandl907a7202008-02-22 12:31:45 +0000399 :keyword:`yield` expression that could receive the value.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000400
401
402.. method:: generator.throw(type[, value[, traceback]])
403
404 Raises an exception of type ``type`` at the point where generator was paused,
405 and returns the next value yielded by the generator function. If the generator
406 exits without yielding another value, a :exc:`StopIteration` exception is
407 raised. If the generator function does not catch the passed-in exception, or
408 raises a different exception, then that exception propagates to the caller.
409
410.. index:: exception: GeneratorExit
411
412
413.. method:: generator.close()
414
415 Raises a :exc:`GeneratorExit` at the point where the generator function was
416 paused. If the generator function then raises :exc:`StopIteration` (by exiting
417 normally, or due to already being closed) or :exc:`GeneratorExit` (by not
418 catching the exception), close returns to its caller. If the generator yields a
419 value, a :exc:`RuntimeError` is raised. If the generator raises any other
420 exception, it is propagated to the caller. :meth:`close` does nothing if the
421 generator has already exited due to an exception or normal exit.
422
423Here is a simple example that demonstrates the behavior of generators and
424generator functions::
425
426 >>> def echo(value=None):
427 ... print "Execution starts when 'next()' is called for the first time."
428 ... try:
429 ... while True:
430 ... try:
431 ... value = (yield value)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000432 ... except Exception, e:
433 ... value = e
434 ... finally:
435 ... print "Don't forget to clean up when 'close()' is called."
436 ...
437 >>> generator = echo(1)
438 >>> print generator.next()
439 Execution starts when 'next()' is called for the first time.
440 1
441 >>> print generator.next()
442 None
443 >>> print generator.send(2)
444 2
445 >>> generator.throw(TypeError, "spam")
446 TypeError('spam',)
447 >>> generator.close()
448 Don't forget to clean up when 'close()' is called.
449
450
451.. seealso::
452
453 :pep:`0342` - Coroutines via Enhanced Generators
454 The proposal to enhance the API and syntax of generators, making them usable as
455 simple coroutines.
456
457
458.. _primaries:
459
460Primaries
461=========
462
463.. index:: single: primary
464
465Primaries represent the most tightly bound operations of the language. Their
466syntax is:
467
468.. productionlist::
469 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
470
471
472.. _attribute-references:
473
474Attribute references
475--------------------
476
477.. index:: pair: attribute; reference
478
479An attribute reference is a primary followed by a period and a name:
480
481.. productionlist::
482 attributeref: `primary` "." `identifier`
483
484.. index::
485 exception: AttributeError
486 object: module
487 object: list
488
489The primary must evaluate to an object of a type that supports attribute
490references, e.g., a module, list, or an instance. This object is then asked to
491produce the attribute whose name is the identifier. If this attribute is not
492available, the exception :exc:`AttributeError` is raised. Otherwise, the type
493and value of the object produced is determined by the object. Multiple
494evaluations of the same attribute reference may yield different objects.
495
496
497.. _subscriptions:
498
499Subscriptions
500-------------
501
502.. index:: single: subscription
503
504.. index::
505 object: sequence
506 object: mapping
507 object: string
508 object: tuple
509 object: list
510 object: dictionary
511 pair: sequence; item
512
513A subscription selects an item of a sequence (string, tuple or list) or mapping
514(dictionary) object:
515
516.. productionlist::
517 subscription: `primary` "[" `expression_list` "]"
518
519The primary must evaluate to an object of a sequence or mapping type.
520
521If the primary is a mapping, the expression list must evaluate to an object
522whose value is one of the keys of the mapping, and the subscription selects the
523value in the mapping that corresponds to that key. (The expression list is a
524tuple except if it has exactly one item.)
525
526If the primary is a sequence, the expression (list) must evaluate to a plain
527integer. 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
529must be a nonnegative integer less than the number of items in the sequence, and
530the subscription selects the item whose index is that value (counting from
531zero).
532
533.. index::
534 single: character
535 pair: string; item
536
537A string's items are characters. A character is not a separate data type but a
538string of exactly one character.
539
540
541.. _slicings:
542
543Slicings
544--------
545
546.. index::
547 single: slicing
548 single: slice
549
550.. index::
551 object: sequence
552 object: string
553 object: tuple
554 object: list
555
556A slicing selects a range of items in a sequence object (e.g., a string, tuple
557or list). Slicings may be used as expressions or as targets in assignment or
558:keyword:`del` statements. The syntax for a slicing:
559
560.. productionlist::
561 slicing: `simple_slicing` | `extended_slicing`
562 simple_slicing: `primary` "[" `short_slice` "]"
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000563 extended_slicing: `primary` "[" `slice_list` "]"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000564 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: "..."
573
574.. index:: pair: extended; slicing
575
576There is ambiguity in the formal syntax here: anything that looks like an
577expression list also looks like a slice list, so any subscription can be
578interpreted as a slicing. Rather than further complicating the syntax, this is
579disambiguated by defining that in this case the interpretation as a subscription
580takes priority over the interpretation as a slicing (this is the case if the
581slice list contains no proper slice nor ellipses). Similarly, when the slice
582list has exactly one short slice and no trailing comma, the interpretation as a
583simple slicing takes priority over that as an extended slicing.
584
585The semantics for a simple slicing are as follows. The primary must evaluate to
586a sequence object. The lower and upper bound expressions, if present, must
587evaluate to plain integers; defaults are zero and the ``sys.maxint``,
588respectively. If either bound is negative, the sequence's length is added to
589it. The slicing now selects all items with index *k* such that ``i <= k < j``
590where *i* and *j* are the specified lower and upper bounds. This may be an
591empty sequence. It is not an error if *i* or *j* lie outside the range of valid
592indexes (such items don't exist so they aren't selected).
593
594.. index::
595 single: start (slice object attribute)
596 single: stop (slice object attribute)
597 single: step (slice object attribute)
598
599The semantics for an extended slicing are as follows. The primary must evaluate
600to a mapping object, and it is indexed with a key that is constructed from the
601slice list, as follows. If the slice list contains at least one comma, the key
602is a tuple containing the conversion of the slice items; otherwise, the
603conversion of the lone slice item is the key. The conversion of a slice item
604that is an expression is that expression. The conversion of an ellipsis slice
605item is the built-in ``Ellipsis`` object. The conversion of a proper slice is a
606slice 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,
608upper bound and stride, respectively, substituting ``None`` for missing
609expressions.
610
611
612.. _calls:
613
614Calls
615-----
616
617.. index:: single: call
618
619.. index:: object: callable
620
621A call calls a callable object (e.g., a function) with a possibly empty series
622of arguments:
623
624.. productionlist::
625 call: `primary` "(" [`argument_list` [","]
626 : | `expression` `genexpr_for`] ")"
627 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000628 : ["," "*" `expression`] ["," `keyword_arguments`]
629 : ["," "**" `expression`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000630 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000631 : ["," "**" `expression`]
632 : | "*" `expression` ["," "*" `expression`] ["," "**" `expression`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000633 : | "**" `expression`
634 positional_arguments: `expression` ("," `expression`)*
635 keyword_arguments: `keyword_item` ("," `keyword_item`)*
636 keyword_item: `identifier` "=" `expression`
637
638A trailing comma may be present after the positional and keyword arguments but
639does not affect the semantics.
640
641The primary must evaluate to a callable object (user-defined functions, built-in
642functions, methods of built-in objects, class objects, methods of class
643instances, and certain class instances themselves are callable; extensions may
644define additional callable object types). All argument expressions are
645evaluated before the call is attempted. Please refer to section :ref:`function`
646for the syntax of formal parameter lists.
647
648If keyword arguments are present, they are first converted to positional
649arguments, as follows. First, a list of unfilled slots is created for the
650formal parameters. If there are N positional arguments, they are placed in the
651first N slots. Next, for each keyword argument, the identifier is used to
652determine the corresponding slot (if the identifier is the same as the first
653formal parameter name, the first slot is used, and so on). If the slot is
654already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
655the 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
657that are still unfilled are filled with the corresponding default value from the
658function definition. (Default values are calculated, once, when the function is
659defined; thus, a mutable object such as a list or dictionary used as default
660value will be shared by all calls that don't specify an argument value for the
661corresponding slot; this should usually be avoided.) If there are any unfilled
662slots for which no default value is specified, a :exc:`TypeError` exception is
663raised. Otherwise, the list of filled slots is used as the argument list for
664the call.
665
Georg Brandl6c14e582009-10-22 11:48:10 +0000666.. impl-detail::
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000667
Georg Brandl6c14e582009-10-22 11:48:10 +0000668 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.
Georg Brandlf8770fb2008-04-27 09:39:59 +0000673
Georg Brandl8ec7f652007-08-15 14:28:01 +0000674If 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
677containing the excess positional arguments (or an empty tuple if there were no
678excess positional arguments).
679
680If 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
683dictionary containing the excess keyword arguments (using the keywords as keys
684and the argument values as corresponding values), or a (new) empty dictionary if
685there were no excess keyword arguments.
686
687If the syntax ``*expression`` appears in the function call, ``expression`` must
688evaluate to a sequence. Elements from this sequence are treated as if they were
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000689additional positional arguments; if there are positional arguments *x1*,...,
690*xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this is
691equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*, ...,
692*yM*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000693
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000694A consequence of this is that although the ``*expression`` syntax may appear
695*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl8ec7f652007-08-15 14:28:01 +0000696(and the ``**expression`` argument, if any -- see below). So::
697
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
709
710It is unusual for both keyword arguments and the ``*expression`` syntax to be
711used in the same call, so in practice this confusion does not arise.
712
713If the syntax ``**expression`` appears in the function call, ``expression`` must
714evaluate to a mapping, the contents of which are treated as additional keyword
715arguments. In the case of a keyword appearing in both ``expression`` and as an
716explicit keyword argument, a :exc:`TypeError` exception is raised.
717
718Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
719used as positional argument slots or as keyword argument names. Formal
720parameters using the syntax ``(sublist)`` cannot be used as keyword argument
721names; the outermost sublist corresponds to a single unnamed argument slot, and
722the argument value is assigned to the sublist using the usual tuple assignment
723rules after all other parameter processing is done.
724
725A call always returns some value, possibly ``None``, unless it raises an
726exception. How this value is computed depends on the type of the callable
727object.
728
729If it is---
730
731a user-defined function:
732 .. index::
733 pair: function; call
734 triple: user-defined; function; call
735 object: user-defined function
736 object: function
737
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.
743
744a 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
754
755 The result is up to the interpreter; see :ref:`built-in-funcs` for the
756 descriptions of built-in functions and methods.
757
758a class object:
759 .. index::
760 object: class
761 pair: class object; call
762
763 A new instance of that class is returned.
764
765a class instance method:
766 .. index::
767 object: class instance
768 object: instance
769 pair: class instance; call
770
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.
774
775a class instance:
776 .. index::
777 pair: instance; call
778 single: __call__() (object method)
779
780 The class must define a :meth:`__call__` method; the effect is then the same as
781 if that method was called.
782
783
784.. _power:
785
786The power operator
787==================
788
789The power operator binds more tightly than unary operators on its left; it binds
790less tightly than unary operators on its right. The syntax is:
791
792.. productionlist::
793 power: `primary` ["**" `u_expr`]
794
795Thus, in an unparenthesized sequence of power and unary operators, the operators
796are evaluated from right to left (this does not constrain the evaluation order
Georg Brandlff457b12007-08-21 06:07:08 +0000797for the operands): ``-1**2`` results in ``-1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000798
799The power operator has the same semantics as the built-in :func:`pow` function,
800when called with two arguments: it yields its left argument raised to the power
801of its right argument. The numeric arguments are first converted to a common
802type. The result type is that of the arguments after coercion.
803
804With mixed operand types, the coercion rules for binary arithmetic operators
805apply. For int and long int operands, the result has the same type as the
806operands (after coercion) unless the second argument is negative; in that case,
807all arguments are converted to float and a float result is delivered. For
808example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last
809feature was added in Python 2.2. In Python 2.1 and before, if both arguments
810were of integer types and the second argument was negative, an exception was
811raised).
812
813Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000814Raising a negative number to a fractional power results in a :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000815
816
817.. _unary:
818
Georg Brandle7cb1ce2009-02-19 08:30:06 +0000819Unary arithmetic and bitwise operations
820=======================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000821
822.. index::
823 triple: unary; arithmetic; operation
Georg Brandlf725b952008-01-05 19:44:22 +0000824 triple: unary; bitwise; operation
Georg Brandl8ec7f652007-08-15 14:28:01 +0000825
Georg Brandle7cb1ce2009-02-19 08:30:06 +0000826All unary arithmetic and bitwise operations have the same priority:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000827
828.. productionlist::
829 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
830
831.. index::
832 single: negation
833 single: minus
834
835The unary ``-`` (minus) operator yields the negation of its numeric argument.
836
837.. index:: single: plus
838
839The unary ``+`` (plus) operator yields its numeric argument unchanged.
840
841.. index:: single: inversion
842
Georg Brandlf725b952008-01-05 19:44:22 +0000843The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
844long integer argument. The bitwise inversion of ``x`` is defined as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000845``-(x+1)``. It only applies to integral numbers.
846
847.. index:: exception: TypeError
848
849In all three cases, if the argument does not have the proper type, a
850:exc:`TypeError` exception is raised.
851
852
853.. _binary:
854
855Binary arithmetic operations
856============================
857
858.. index:: triple: binary; arithmetic; operation
859
860The binary arithmetic operations have the conventional priority levels. Note
861that some of these operations also apply to certain non-numeric types. Apart
862from the power operator, there are only two levels, one for multiplicative
863operators and one for additive operators:
864
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`
869
870.. index:: single: multiplication
871
872The ``*`` (multiplication) operator yields the product of its arguments. The
873arguments must either both be numbers, or one argument must be an integer (plain
874or long) and the other must be a sequence. In the former case, the numbers are
875converted to a common type and then multiplied together. In the latter case,
876sequence repetition is performed; a negative repetition factor yields an empty
877sequence.
878
879.. index::
880 exception: ZeroDivisionError
881 single: division
882
883The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
884their arguments. The numeric arguments are first converted to a common type.
885Plain or long integer division yields an integer of the same type; the result is
886that of mathematical division with the 'floor' function applied to the result.
887Division by zero raises the :exc:`ZeroDivisionError` exception.
888
889.. index:: single: modulo
890
891The ``%`` (modulo) operator yields the remainder from the division of the first
892argument by the second. The numeric arguments are first converted to a common
893type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
894arguments 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
896result with the same sign as its second operand (or zero); the absolute value of
897the result is strictly smaller than the absolute value of the second operand
898[#]_.
899
900The integer division and modulo operators are connected by the following
901identity: ``x == (x/y)*y + (x%y)``. Integer division and modulo are also
902connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y,
903x%y)``. These identities don't hold for floating point numbers; there similar
904identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
905``floor(x/y) - 1`` [#]_.
906
907In addition to performing the modulo operation on numbers, the ``%`` operator is
908also overloaded by string and unicode objects to perform string formatting (also
909known as interpolation). The syntax for string formatting is described in the
910Python Library Reference, section :ref:`string-formatting`.
911
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.
916
917.. index:: single: addition
918
919The ``+`` (addition) operator yields the sum of its arguments. The arguments
920must either both be numbers or both sequences of the same type. In the former
921case, the numbers are converted to a common type and then added together. In
922the latter case, the sequences are concatenated.
923
924.. index:: single: subtraction
925
926The ``-`` (subtraction) operator yields the difference of its arguments. The
927numeric arguments are first converted to a common type.
928
929
930.. _shifting:
931
932Shifting operations
933===================
934
935.. index:: pair: shifting; operation
936
937The shifting operations have lower priority than the arithmetic operations:
938
939.. productionlist::
940 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
941
942These operators accept plain or long integers as arguments. The arguments are
943converted to a common type. They shift the first argument to the left or right
944by the number of bits given by the second argument.
945
946.. index:: exception: ValueError
947
Georg Brandle9135ba2008-05-11 10:55:59 +0000948A right shift by *n* bits is defined as division by ``pow(2, n)``. A left shift
949by *n* bits is defined as multiplication with ``pow(2, n)``. Negative shift
950counts raise a :exc:`ValueError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000951
952
953.. _bitwise:
954
Georg Brandlf725b952008-01-05 19:44:22 +0000955Binary bitwise operations
956=========================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000957
Georg Brandlf725b952008-01-05 19:44:22 +0000958.. index:: triple: binary; bitwise; operation
Georg Brandl8ec7f652007-08-15 14:28:01 +0000959
960Each of the three bitwise operations has a different priority level:
961
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`
966
Georg Brandlf725b952008-01-05 19:44:22 +0000967.. index:: pair: bitwise; and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000968
969The ``&`` operator yields the bitwise AND of its arguments, which must be plain
970or long integers. The arguments are converted to a common type.
971
972.. index::
Georg Brandlf725b952008-01-05 19:44:22 +0000973 pair: bitwise; xor
Georg Brandl8ec7f652007-08-15 14:28:01 +0000974 pair: exclusive; or
975
976The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
977must be plain or long integers. The arguments are converted to a common type.
978
979.. index::
Georg Brandlf725b952008-01-05 19:44:22 +0000980 pair: bitwise; or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000981 pair: inclusive; or
982
983The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
984must be plain or long integers. The arguments are converted to a common type.
985
986
987.. _comparisons:
Georg Brandlb19be572007-12-29 10:57:00 +0000988.. _is:
989.. _isnot:
990.. _in:
991.. _notin:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000992
993Comparisons
994===========
995
996.. index:: single: comparison
997
998.. index:: pair: C; language
999
1000Unlike C, all comparison operations in Python have the same priority, which is
1001lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1002C, expressions like ``a < b < c`` have the interpretation that is conventional
1003in mathematics:
1004
1005.. productionlist::
1006 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1007 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
1008 : | "is" ["not"] | ["not"] "in"
1009
1010Comparisons yield boolean values: ``True`` or ``False``.
1011
1012.. index:: pair: chaining; comparisons
1013
1014Comparisons 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
1016cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1017
Georg Brandl32008322007-08-21 06:12:19 +00001018Formally, 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
1020to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1021evaluated at most once.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001022
Georg Brandl32008322007-08-21 06:12:19 +00001023Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl8ec7f652007-08-15 14:28:01 +00001024*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1025pretty).
1026
1027The forms ``<>`` and ``!=`` are equivalent; for consistency with C, ``!=`` is
1028preferred; where ``!=`` is mentioned below ``<>`` is also accepted. The ``<>``
1029spelling is considered obsolescent.
1030
1031The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1032values of two objects. The objects need not have the same type. If both are
1033numbers, they are converted to a common type. Otherwise, objects of different
1034types *always* compare unequal, and are ordered consistently but arbitrarily.
Georg Brandld7d4fd72009-07-26 14:37:28 +00001035You can control comparison behavior of objects of non-built-in types by defining
Georg Brandl8ec7f652007-08-15 14:28:01 +00001036a ``__cmp__`` method or rich comparison methods like ``__gt__``, described in
1037section :ref:`specialnames`.
1038
1039(This unusual definition of comparison was used to simplify the definition of
1040operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
1041In the future, the comparison rules for objects of different types are likely to
1042change.)
1043
1044Comparison of objects of the same type depends on the type:
1045
1046* Numbers are compared arithmetically.
1047
1048* Strings are compared lexicographically using the numeric equivalents (the
1049 result of the built-in function :func:`ord`) of their characters. Unicode and
Mark Summerfield216ad332007-08-16 10:09:22 +00001050 8-bit strings are fully interoperable in this behavior. [#]_
Georg Brandl8ec7f652007-08-15 14:28:01 +00001051
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.
1056
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]``).
1061
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. [#]_
1065
Georg Brandld7d4fd72009-07-26 14:37:28 +00001066* Most other objects of built-in types compare unequal unless they are the same
Georg Brandl8ec7f652007-08-15 14:28:01 +00001067 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.
1070
Georg Brandl489343e2008-03-28 12:24:51 +00001071The operators :keyword:`in` and :keyword:`not in` test for collection
1072membership. ``x in s`` evaluates to true if *x* is a member of the collection
1073*s*, and false otherwise. ``x not in s`` returns the negation of ``x in s``.
1074The collection membership test has traditionally been bound to sequences; an
1075object is a member of a collection if the collection is a sequence and contains
1076an element equal to that object. However, it make sense for many other object
1077types to support membership tests without being a sequence. In particular,
1078dictionaries (for keys) and sets support membership testing.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001079
1080For the list and tuple types, ``x in y`` is true if and only if there exists an
1081index *i* such that ``x == y[i]`` is true.
1082
1083For the Unicode and string types, ``x in y`` is true if and only if *x* is a
1084substring of *y*. An equivalent test is ``y.find(x) != -1``. Note, *x* and *y*
1085need not be the same type; consequently, ``u'ab' in 'abc'`` will return
1086``True``. Empty strings are always considered to be a substring of any other
1087string, so ``"" in "abc"`` will return ``True``.
1088
1089.. versionchanged:: 2.3
1090 Previously, *x* was required to be a string of length ``1``.
1091
1092For user-defined classes which define the :meth:`__contains__` method, ``x in
1093y`` is true if and only if ``y.__contains__(x)`` is true.
1094
1095For user-defined classes which do not define :meth:`__contains__` and do define
1096:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1097integer index *i* such that ``x == y[i]``, and all lower integer indices do not
1098raise :exc:`IndexError` exception. (If any other exception is raised, it is as
1099if :keyword:`in` raised that exception).
1100
1101.. index::
1102 operator: in
1103 operator: not in
1104 pair: membership; test
1105 object: sequence
1106
1107The operator :keyword:`not in` is defined to have the inverse true value of
1108:keyword:`in`.
1109
1110.. index::
1111 operator: is
1112 operator: is not
1113 pair: identity; test
1114
1115The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1116is y`` is true if and only if *x* and *y* are the same object. ``x is not y``
Georg Brandl3214a012008-07-01 20:50:02 +00001117yields the inverse truth value. [#]_
Georg Brandl8ec7f652007-08-15 14:28:01 +00001118
1119
1120.. _booleans:
Georg Brandlb19be572007-12-29 10:57:00 +00001121.. _and:
1122.. _or:
1123.. _not:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001124
1125Boolean operations
1126==================
1127
1128.. index::
1129 pair: Conditional; expression
1130 pair: Boolean; operation
1131
1132Boolean operations have the lowest priority of all Python operations:
1133
1134.. productionlist::
1135 expression: `conditional_expression` | `lambda_form`
1136 old_expression: `or_test` | `old_lambda_form`
1137 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1138 or_test: `and_test` | `or_test` "or" `and_test`
1139 and_test: `not_test` | `and_test` "and" `not_test`
1140 not_test: `comparison` | "not" `not_test`
1141
1142In the context of Boolean operations, and also when expressions are used by
1143control flow statements, the following values are interpreted as false:
1144``False``, ``None``, numeric zero of all types, and empty strings and containers
1145(including strings, tuples, lists, dictionaries, sets and frozensets). All
Benjamin Petersonfe7c26d2008-09-23 13:32:46 +00001146other values are interpreted as true. (See the :meth:`~object.__nonzero__`
1147special method for a way to change this.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001148
1149.. index:: operator: not
1150
1151The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1152otherwise.
1153
1154The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is
1155true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated
1156and its value is returned.
1157
1158.. versionadded:: 2.5
1159
1160.. index:: operator: and
1161
1162The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1163returned; otherwise, *y* is evaluated and the resulting value is returned.
1164
1165.. index:: operator: or
1166
1167The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1168returned; otherwise, *y* is evaluated and the resulting value is returned.
1169
1170(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1171they return to ``False`` and ``True``, but rather return the last evaluated
1172argument. This is sometimes useful, e.g., if ``s`` is a string that should be
1173replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1174the desired value. Because :keyword:`not` has to invent a value anyway, it does
1175not bother to return a value of the same type as its argument, so e.g., ``not
1176'foo'`` yields ``False``, not ``''``.)
1177
1178
1179.. _lambdas:
Georg Brandl5623e502009-04-10 08:16:47 +00001180.. _lambda:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001181
1182Lambdas
1183=======
1184
1185.. index::
1186 pair: lambda; expression
1187 pair: lambda; form
1188 pair: anonymous; function
1189
1190.. productionlist::
1191 lambda_form: "lambda" [`parameter_list`]: `expression`
1192 old_lambda_form: "lambda" [`parameter_list`]: `old_expression`
1193
1194Lambda forms (lambda expressions) have the same syntactic position as
1195expressions. They are a shorthand to create anonymous functions; the expression
1196``lambda arguments: expression`` yields a function object. The unnamed object
1197behaves like a function object defined with ::
1198
1199 def name(arguments):
1200 return expression
1201
1202See section :ref:`function` for the syntax of parameter lists. Note that
1203functions created with lambda forms cannot contain statements.
1204
Georg Brandl8ec7f652007-08-15 14:28:01 +00001205
1206.. _exprlists:
1207
1208Expression lists
1209================
1210
1211.. index:: pair: expression; list
1212
1213.. productionlist::
1214 expression_list: `expression` ( "," `expression` )* [","]
1215
1216.. index:: object: tuple
1217
1218An expression list containing at least one comma yields a tuple. The length of
1219the tuple is the number of expressions in the list. The expressions are
1220evaluated from left to right.
1221
1222.. index:: pair: trailing; comma
1223
1224The trailing comma is required only to create a single tuple (a.k.a. a
1225*singleton*); it is optional in all other cases. A single expression without a
1226trailing comma doesn't create a tuple, but rather yields the value of that
1227expression. (To create an empty tuple, use an empty pair of parentheses:
1228``()``.)
1229
1230
1231.. _evalorder:
1232
1233Evaluation order
1234================
1235
1236.. index:: pair: evaluation; order
1237
1238Python evaluates expressions from left to right. Notice that while evaluating an
1239assignment, the right-hand side is evaluated before the left-hand side.
1240
1241In the following lines, expressions will be evaluated in the arithmetic order of
1242their suffixes::
1243
1244 expr1, expr2, expr3, expr4
1245 (expr1, expr2, expr3, expr4)
1246 {expr1: expr2, expr3: expr4}
1247 expr1 + expr2 * (expr3 - expr4)
Georg Brandl463f39d2008-08-08 06:42:20 +00001248 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001249 expr3, expr4 = expr1, expr2
1250
1251
1252.. _operator-summary:
1253
1254Summary
1255=======
1256
1257.. index:: pair: operator; precedence
1258
1259The following table summarizes the operator precedences in Python, from lowest
1260precedence (least binding) to highest precedence (most binding). Operators in
1261the same box have the same precedence. Unless the syntax is explicitly given,
1262operators are binary. Operators in the same box group left to right (except for
1263comparisons, including tests, which all have the same precedence and chain from
1264left to right --- see section :ref:`comparisons` --- and exponentiation, which
1265groups from right to left).
1266
1267+-----------------------------------------------+-------------------------------------+
1268| Operator | Description |
1269+===============================================+=====================================+
1270| :keyword:`lambda` | Lambda expression |
1271+-----------------------------------------------+-------------------------------------+
1272| :keyword:`or` | Boolean OR |
1273+-----------------------------------------------+-------------------------------------+
1274| :keyword:`and` | Boolean AND |
1275+-----------------------------------------------+-------------------------------------+
1276| :keyword:`not` *x* | Boolean NOT |
1277+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001278| :keyword:`in`, :keyword:`not` :keyword:`in`, | Comparisons, including membership |
1279| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests, |
1280| ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==`` | |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001281+-----------------------------------------------+-------------------------------------+
1282| ``|`` | Bitwise OR |
1283+-----------------------------------------------+-------------------------------------+
1284| ``^`` | Bitwise XOR |
1285+-----------------------------------------------+-------------------------------------+
1286| ``&`` | Bitwise AND |
1287+-----------------------------------------------+-------------------------------------+
1288| ``<<``, ``>>`` | Shifts |
1289+-----------------------------------------------+-------------------------------------+
1290| ``+``, ``-`` | Addition and subtraction |
1291+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001292| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001293+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001294| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001295+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001296| ``**`` | Exponentiation [#]_ |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001297+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001298| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1299| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001300+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001301| ``(expressions...)``, | Binding or tuple display, |
1302| ``[expressions...]``, | list display, |
1303| ``{key:datum...}``, | dictionary display, |
1304| ```expressions...``` | string conversion |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001305+-----------------------------------------------+-------------------------------------+
1306
1307.. rubric:: Footnotes
1308
Martin v. Löwis0b667312008-05-23 19:33:13 +00001309.. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001310 variables of each ``for`` it contains into the containing scope. However, this
Martin v. Löwis0b667312008-05-23 19:33:13 +00001311 behavior is deprecated, and relying on it will not work in Python 3.0
Georg Brandl8ec7f652007-08-15 14:28:01 +00001312
1313.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1314 true numerically due to roundoff. For example, and assuming a platform on which
1315 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1316 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1317 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod`
1318 in the :mod:`math` module returns a result whose sign matches the sign of the
1319 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1320 is more appropriate depends on the application.
1321
1322.. [#] If x is very close to an exact integer multiple of y, it's possible for
1323 ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding. In such
1324 cases, Python returns the latter result, in order to preserve that
1325 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1326
Mark Summerfield216ad332007-08-16 10:09:22 +00001327.. [#] While comparisons between unicode strings make sense at the byte
1328 level, they may be counter-intuitive to users. For example, the
Mark Summerfieldd92e8712007-10-03 08:53:21 +00001329 strings ``u"\u00C7"`` and ``u"\u0043\u0327"`` compare differently,
Mark Summerfield216ad332007-08-16 10:09:22 +00001330 even though they both represent the same unicode character (LATIN
Mark Summerfieldd92e8712007-10-03 08:53:21 +00001331 CAPTITAL LETTER C WITH CEDILLA). To compare strings in a human
1332 recognizable way, compare using :func:`unicodedata.normalize`.
Mark Summerfield216ad332007-08-16 10:09:22 +00001333
Georg Brandl8ec7f652007-08-15 14:28:01 +00001334.. [#] The implementation computes this efficiently, without constructing lists or
1335 sorting.
1336
1337.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
1338 value) lists, but this was very expensive for the common case of comparing for
1339 equality. An even earlier version of Python compared dictionaries by identity
1340 only, but this caused surprises because people expected to be able to test a
1341 dictionary for emptiness by comparing it to ``{}``.
1342
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001343.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Georg Brandl3214a012008-07-01 20:50:02 +00001344 descriptors, you may notice seemingly unusual behaviour in certain uses of
1345 the :keyword:`is` operator, like those involving comparisons between instance
1346 methods, or constants. Check their documentation for more info.
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001347
1348.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1349 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.