blob: 8bfc8d9ae9c5693c74562d08a262c6d0a3bf76eb [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`)+ [","]]
Georg Brandl5a7eca12010-03-21 19:29:04 +0000188 old_expression: `or_test` | `old_lambda_form`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000189 list_iter: `list_for` | `list_if`
190 list_if: "if" `old_expression` [`list_iter`]
191
192.. index::
193 pair: list; comprehensions
194 object: list
195 pair: empty; list
196
197A list display yields a new list object. Its contents are specified by
198providing either a list of expressions or a list comprehension. When a
199comma-separated list of expressions is supplied, its elements are evaluated from
200left to right and placed into the list object in that order. When a list
201comprehension is supplied, it consists of a single expression followed by at
202least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if`
203clauses. In this case, the elements of the new list are those that would be
204produced by considering each of the :keyword:`for` or :keyword:`if` clauses a
205block, nesting from left to right, and evaluating the expression to produce a
206list element each time the innermost block is reached [#]_.
207
208
209.. _genexpr:
210
211Generator expressions
212---------------------
213
214.. index:: pair: generator; expression
215
216A generator expression is a compact generator notation in parentheses:
217
218.. productionlist::
219 generator_expression: "(" `expression` `genexpr_for` ")"
220 genexpr_for: "for" `target_list` "in" `or_test` [`genexpr_iter`]
221 genexpr_iter: `genexpr_for` | `genexpr_if`
222 genexpr_if: "if" `old_expression` [`genexpr_iter`]
223
224.. index:: object: generator
225
226A generator expression yields a new generator object. It consists of a single
227expression followed by at least one :keyword:`for` clause and zero or more
228:keyword:`for` or :keyword:`if` clauses. The iterating values of the new
229generator are those that would be produced by considering each of the
230:keyword:`for` or :keyword:`if` clauses a block, nesting from left to right, and
231evaluating the expression to yield a value that is reached the innermost block
232for each iteration.
233
Georg Brandl8e67ef52008-03-03 21:31:50 +0000234Variables used in the generator expression are evaluated lazily in a separate
235scope when the :meth:`next` method is called for the generator object (in the
236same fashion as for normal generators). However, the :keyword:`in` expression
237of the leftmost :keyword:`for` clause is immediately evaluated in the current
238scope so that an error produced by it can be seen before any other possible
239error in the code that handles the generator expression. Subsequent
240:keyword:`for` and :keyword:`if` clauses cannot be evaluated immediately since
241they may depend on the previous :keyword:`for` loop. For example:
242``(x*y for x in range(10) for y in bar(x))``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000243
244The parentheses can be omitted on calls with only one argument. See section
245:ref:`calls` for the detail.
246
247
248.. _dict:
249
250Dictionary displays
251-------------------
252
253.. index:: pair: dictionary; display
254
255.. index::
256 single: key
257 single: datum
258 single: key/datum pair
259
260A dictionary display is a possibly empty series of key/datum pairs enclosed in
261curly braces:
262
263.. productionlist::
264 dict_display: "{" [`key_datum_list`] "}"
265 key_datum_list: `key_datum` ("," `key_datum`)* [","]
266 key_datum: `expression` ":" `expression`
267
268.. index:: object: dictionary
269
270A dictionary display yields a new dictionary object.
271
272The key/datum pairs are evaluated from left to right to define the entries of
273the dictionary: each key object is used as a key into the dictionary to store
274the corresponding datum.
275
276.. index:: pair: immutable; object
277
278Restrictions on the types of the key values are listed earlier in section
Georg Brandl7c3e79f2007-11-02 20:06:17 +0000279:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000280all mutable objects.) Clashes between duplicate keys are not detected; the last
281datum (textually rightmost in the display) stored for a given key value
282prevails.
283
284
285.. _string-conversions:
286
287String conversions
288------------------
289
290.. index::
291 pair: string; conversion
292 pair: reverse; quotes
293 pair: backward; quotes
294 single: back-quotes
295
296A string conversion is an expression list enclosed in reverse (a.k.a. backward)
297quotes:
298
299.. productionlist::
300 string_conversion: "'" `expression_list` "'"
301
302A string conversion evaluates the contained expression list and converts the
303resulting object into a string according to rules specific to its type.
304
305If the object is a string, a number, ``None``, or a tuple, list or dictionary
306containing only objects whose type is one of these, the resulting string is a
307valid Python expression which can be passed to the built-in function
308:func:`eval` to yield an expression with the same value (or an approximation, if
309floating point numbers are involved).
310
311(In particular, converting a string adds quotes around it and converts "funny"
312characters to escape sequences that are safe to print.)
313
314.. index:: object: recursive
315
316Recursive objects (for example, lists or dictionaries that contain a reference
317to themselves, directly or indirectly) use ``...`` to indicate a recursive
318reference, and the result cannot be passed to :func:`eval` to get an equal value
319(:exc:`SyntaxError` will be raised instead).
320
321.. index::
322 builtin: repr
323 builtin: str
324
325The built-in function :func:`repr` performs exactly the same conversion in its
326argument as enclosing it in parentheses and reverse quotes does. The built-in
327function :func:`str` performs a similar but more user-friendly conversion.
328
329
330.. _yieldexpr:
331
332Yield expressions
333-----------------
334
335.. index::
336 keyword: yield
337 pair: yield; expression
338 pair: generator; function
339
340.. productionlist::
341 yield_atom: "(" `yield_expression` ")"
342 yield_expression: "yield" [`expression_list`]
343
344.. versionadded:: 2.5
345
346The :keyword:`yield` expression is only used when defining a generator function,
347and can only be used in the body of a function definition. Using a
348:keyword:`yield` expression in a function definition is sufficient to cause that
349definition to create a generator function instead of a normal function.
350
351When a generator function is called, it returns an iterator known as a
352generator. That generator then controls the execution of a generator function.
353The execution starts when one of the generator's methods is called. At that
354time, the execution proceeds to the first :keyword:`yield` expression, where it
355is suspended again, returning the value of :token:`expression_list` to
356generator's caller. By suspended we mean that all local state is retained,
357including the current bindings of local variables, the instruction pointer, and
358the internal evaluation stack. When the execution is resumed by calling one of
359the generator's methods, the function can proceed exactly as if the
360:keyword:`yield` expression was just another external call. The value of the
361:keyword:`yield` expression after resuming depends on the method which resumed
362the execution.
363
364.. index:: single: coroutine
365
366All of this makes generator functions quite similar to coroutines; they yield
367multiple times, they have more than one entry point and their execution can be
368suspended. The only difference is that a generator function cannot control
369where should the execution continue after it yields; the control is always
370transfered to the generator's caller.
371
372.. index:: object: generator
373
374The following generator's methods can be used to control the execution of a
375generator function:
376
377.. index:: exception: StopIteration
378
379
380.. method:: generator.next()
381
382 Starts the execution of a generator function or resumes it at the last executed
383 :keyword:`yield` expression. When a generator function is resumed with a
384 :meth:`next` method, the current :keyword:`yield` expression always evaluates to
385 :const:`None`. The execution then continues to the next :keyword:`yield`
386 expression, where the generator is suspended again, and the value of the
387 :token:`expression_list` is returned to :meth:`next`'s caller. If the generator
388 exits without yielding another value, a :exc:`StopIteration` exception is
389 raised.
390
391
392.. method:: generator.send(value)
393
394 Resumes the execution and "sends" a value into the generator function. The
395 ``value`` argument becomes the result of the current :keyword:`yield`
396 expression. The :meth:`send` method returns the next value yielded by the
397 generator, or raises :exc:`StopIteration` if the generator exits without
398 yielding another value. When :meth:`send` is called to start the generator, it
399 must be called with :const:`None` as the argument, because there is no
Georg Brandl907a7202008-02-22 12:31:45 +0000400 :keyword:`yield` expression that could receive the value.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000401
402
403.. method:: generator.throw(type[, value[, traceback]])
404
405 Raises an exception of type ``type`` at the point where generator was paused,
406 and returns the next value yielded by the generator function. If the generator
407 exits without yielding another value, a :exc:`StopIteration` exception is
408 raised. If the generator function does not catch the passed-in exception, or
409 raises a different exception, then that exception propagates to the caller.
410
411.. index:: exception: GeneratorExit
412
413
414.. method:: generator.close()
415
416 Raises a :exc:`GeneratorExit` at the point where the generator function was
417 paused. If the generator function then raises :exc:`StopIteration` (by exiting
418 normally, or due to already being closed) or :exc:`GeneratorExit` (by not
419 catching the exception), close returns to its caller. If the generator yields a
420 value, a :exc:`RuntimeError` is raised. If the generator raises any other
421 exception, it is propagated to the caller. :meth:`close` does nothing if the
422 generator has already exited due to an exception or normal exit.
423
424Here is a simple example that demonstrates the behavior of generators and
425generator functions::
426
427 >>> def echo(value=None):
428 ... print "Execution starts when 'next()' is called for the first time."
429 ... try:
430 ... while True:
431 ... try:
432 ... value = (yield value)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000433 ... except Exception, e:
434 ... value = e
435 ... finally:
436 ... print "Don't forget to clean up when 'close()' is called."
437 ...
438 >>> generator = echo(1)
439 >>> print generator.next()
440 Execution starts when 'next()' is called for the first time.
441 1
442 >>> print generator.next()
443 None
444 >>> print generator.send(2)
445 2
446 >>> generator.throw(TypeError, "spam")
447 TypeError('spam',)
448 >>> generator.close()
449 Don't forget to clean up when 'close()' is called.
450
451
452.. seealso::
453
454 :pep:`0342` - Coroutines via Enhanced Generators
455 The proposal to enhance the API and syntax of generators, making them usable as
456 simple coroutines.
457
458
459.. _primaries:
460
461Primaries
462=========
463
464.. index:: single: primary
465
466Primaries represent the most tightly bound operations of the language. Their
467syntax is:
468
469.. productionlist::
470 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
471
472
473.. _attribute-references:
474
475Attribute references
476--------------------
477
478.. index:: pair: attribute; reference
479
480An attribute reference is a primary followed by a period and a name:
481
482.. productionlist::
483 attributeref: `primary` "." `identifier`
484
485.. index::
486 exception: AttributeError
487 object: module
488 object: list
489
490The primary must evaluate to an object of a type that supports attribute
491references, e.g., a module, list, or an instance. This object is then asked to
492produce the attribute whose name is the identifier. If this attribute is not
493available, the exception :exc:`AttributeError` is raised. Otherwise, the type
494and value of the object produced is determined by the object. Multiple
495evaluations of the same attribute reference may yield different objects.
496
497
498.. _subscriptions:
499
500Subscriptions
501-------------
502
503.. index:: single: subscription
504
505.. index::
506 object: sequence
507 object: mapping
508 object: string
509 object: tuple
510 object: list
511 object: dictionary
512 pair: sequence; item
513
514A subscription selects an item of a sequence (string, tuple or list) or mapping
515(dictionary) object:
516
517.. productionlist::
518 subscription: `primary` "[" `expression_list` "]"
519
520The primary must evaluate to an object of a sequence or mapping type.
521
522If the primary is a mapping, the expression list must evaluate to an object
523whose value is one of the keys of the mapping, and the subscription selects the
524value in the mapping that corresponds to that key. (The expression list is a
525tuple except if it has exactly one item.)
526
527If the primary is a sequence, the expression (list) must evaluate to a plain
528integer. If this value is negative, the length of the sequence is added to it
529(so that, e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value
530must be a nonnegative integer less than the number of items in the sequence, and
531the subscription selects the item whose index is that value (counting from
532zero).
533
534.. index::
535 single: character
536 pair: string; item
537
538A string's items are characters. A character is not a separate data type but a
539string of exactly one character.
540
541
542.. _slicings:
543
544Slicings
545--------
546
547.. index::
548 single: slicing
549 single: slice
550
551.. index::
552 object: sequence
553 object: string
554 object: tuple
555 object: list
556
557A slicing selects a range of items in a sequence object (e.g., a string, tuple
558or list). Slicings may be used as expressions or as targets in assignment or
559:keyword:`del` statements. The syntax for a slicing:
560
561.. productionlist::
562 slicing: `simple_slicing` | `extended_slicing`
563 simple_slicing: `primary` "[" `short_slice` "]"
Georg Brandl734373c2009-01-03 21:55:17 +0000564 extended_slicing: `primary` "[" `slice_list` "]"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000565 slice_list: `slice_item` ("," `slice_item`)* [","]
566 slice_item: `expression` | `proper_slice` | `ellipsis`
567 proper_slice: `short_slice` | `long_slice`
568 short_slice: [`lower_bound`] ":" [`upper_bound`]
569 long_slice: `short_slice` ":" [`stride`]
570 lower_bound: `expression`
571 upper_bound: `expression`
572 stride: `expression`
573 ellipsis: "..."
574
575.. index:: pair: extended; slicing
576
577There is ambiguity in the formal syntax here: anything that looks like an
578expression list also looks like a slice list, so any subscription can be
579interpreted as a slicing. Rather than further complicating the syntax, this is
580disambiguated by defining that in this case the interpretation as a subscription
581takes priority over the interpretation as a slicing (this is the case if the
582slice list contains no proper slice nor ellipses). Similarly, when the slice
583list has exactly one short slice and no trailing comma, the interpretation as a
584simple slicing takes priority over that as an extended slicing.
585
586The semantics for a simple slicing are as follows. The primary must evaluate to
587a sequence object. The lower and upper bound expressions, if present, must
588evaluate to plain integers; defaults are zero and the ``sys.maxint``,
589respectively. If either bound is negative, the sequence's length is added to
590it. The slicing now selects all items with index *k* such that ``i <= k < j``
591where *i* and *j* are the specified lower and upper bounds. This may be an
592empty sequence. It is not an error if *i* or *j* lie outside the range of valid
593indexes (such items don't exist so they aren't selected).
594
595.. index::
596 single: start (slice object attribute)
597 single: stop (slice object attribute)
598 single: step (slice object attribute)
599
600The semantics for an extended slicing are as follows. The primary must evaluate
601to a mapping object, and it is indexed with a key that is constructed from the
602slice list, as follows. If the slice list contains at least one comma, the key
603is a tuple containing the conversion of the slice items; otherwise, the
604conversion of the lone slice item is the key. The conversion of a slice item
605that is an expression is that expression. The conversion of an ellipsis slice
606item is the built-in ``Ellipsis`` object. The conversion of a proper slice is a
607slice object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
608:attr:`step` attributes are the values of the expressions given as lower bound,
609upper bound and stride, respectively, substituting ``None`` for missing
610expressions.
611
612
613.. _calls:
614
615Calls
616-----
617
618.. index:: single: call
619
620.. index:: object: callable
621
622A call calls a callable object (e.g., a function) with a possibly empty series
623of arguments:
624
625.. productionlist::
626 call: `primary` "(" [`argument_list` [","]
627 : | `expression` `genexpr_for`] ")"
628 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000629 : ["," "*" `expression`] ["," `keyword_arguments`]
630 : ["," "**" `expression`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000631 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000632 : ["," "**" `expression`]
633 : | "*" `expression` ["," "*" `expression`] ["," "**" `expression`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000634 : | "**" `expression`
635 positional_arguments: `expression` ("," `expression`)*
636 keyword_arguments: `keyword_item` ("," `keyword_item`)*
637 keyword_item: `identifier` "=" `expression`
638
639A trailing comma may be present after the positional and keyword arguments but
640does not affect the semantics.
641
642The primary must evaluate to a callable object (user-defined functions, built-in
643functions, methods of built-in objects, class objects, methods of class
644instances, and certain class instances themselves are callable; extensions may
645define additional callable object types). All argument expressions are
646evaluated before the call is attempted. Please refer to section :ref:`function`
647for the syntax of formal parameter lists.
648
649If keyword arguments are present, they are first converted to positional
650arguments, as follows. First, a list of unfilled slots is created for the
651formal parameters. If there are N positional arguments, they are placed in the
652first N slots. Next, for each keyword argument, the identifier is used to
653determine the corresponding slot (if the identifier is the same as the first
654formal parameter name, the first slot is used, and so on). If the slot is
655already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
656the argument is placed in the slot, filling it (even if the expression is
657``None``, it fills the slot). When all arguments have been processed, the slots
658that are still unfilled are filled with the corresponding default value from the
659function definition. (Default values are calculated, once, when the function is
660defined; thus, a mutable object such as a list or dictionary used as default
661value will be shared by all calls that don't specify an argument value for the
662corresponding slot; this should usually be avoided.) If there are any unfilled
663slots for which no default value is specified, a :exc:`TypeError` exception is
664raised. Otherwise, the list of filled slots is used as the argument list for
665the call.
666
Georg Brandl5d2eb342009-10-27 15:08:27 +0000667.. impl-detail::
Georg Brandl734373c2009-01-03 21:55:17 +0000668
Georg Brandl5d2eb342009-10-27 15:08:27 +0000669 An implementation may provide built-in functions whose positional parameters
670 do not have names, even if they are 'named' for the purpose of documentation,
671 and which therefore cannot be supplied by keyword. In CPython, this is the
672 case for functions implemented in C that use :cfunc:`PyArg_ParseTuple` to
673 parse their arguments.
Georg Brandlf8770fb2008-04-27 09:39:59 +0000674
Georg Brandl8ec7f652007-08-15 14:28:01 +0000675If there are more positional arguments than there are formal parameter slots, a
676:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
677``*identifier`` is present; in this case, that formal parameter receives a tuple
678containing the excess positional arguments (or an empty tuple if there were no
679excess positional arguments).
680
681If any keyword argument does not correspond to a formal parameter name, a
682:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
683``**identifier`` is present; in this case, that formal parameter receives a
684dictionary containing the excess keyword arguments (using the keywords as keys
685and the argument values as corresponding values), or a (new) empty dictionary if
686there were no excess keyword arguments.
687
688If the syntax ``*expression`` appears in the function call, ``expression`` must
689evaluate to a sequence. Elements from this sequence are treated as if they were
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000690additional positional arguments; if there are positional arguments *x1*,...,
691*xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this is
692equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*, ...,
693*yM*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000694
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000695A consequence of this is that although the ``*expression`` syntax may appear
696*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl8ec7f652007-08-15 14:28:01 +0000697(and the ``**expression`` argument, if any -- see below). So::
698
699 >>> def f(a, b):
700 ... print a, b
701 ...
702 >>> f(b=1, *(2,))
703 2 1
704 >>> f(a=1, *(2,))
705 Traceback (most recent call last):
706 File "<stdin>", line 1, in ?
707 TypeError: f() got multiple values for keyword argument 'a'
708 >>> f(1, *(2,))
709 1 2
710
711It is unusual for both keyword arguments and the ``*expression`` syntax to be
712used in the same call, so in practice this confusion does not arise.
713
714If the syntax ``**expression`` appears in the function call, ``expression`` must
715evaluate to a mapping, the contents of which are treated as additional keyword
716arguments. In the case of a keyword appearing in both ``expression`` and as an
717explicit keyword argument, a :exc:`TypeError` exception is raised.
718
719Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
720used as positional argument slots or as keyword argument names. Formal
721parameters using the syntax ``(sublist)`` cannot be used as keyword argument
722names; the outermost sublist corresponds to a single unnamed argument slot, and
723the argument value is assigned to the sublist using the usual tuple assignment
724rules after all other parameter processing is done.
725
726A call always returns some value, possibly ``None``, unless it raises an
727exception. How this value is computed depends on the type of the callable
728object.
729
730If it is---
731
732a user-defined function:
733 .. index::
734 pair: function; call
735 triple: user-defined; function; call
736 object: user-defined function
737 object: function
738
739 The code block for the function is executed, passing it the argument list. The
740 first thing the code block will do is bind the formal parameters to the
741 arguments; this is described in section :ref:`function`. When the code block
742 executes a :keyword:`return` statement, this specifies the return value of the
743 function call.
744
745a built-in function or method:
746 .. index::
747 pair: function; call
748 pair: built-in function; call
749 pair: method; call
750 pair: built-in method; call
751 object: built-in method
752 object: built-in function
753 object: method
754 object: function
755
756 The result is up to the interpreter; see :ref:`built-in-funcs` for the
757 descriptions of built-in functions and methods.
758
759a class object:
760 .. index::
761 object: class
762 pair: class object; call
763
764 A new instance of that class is returned.
765
766a class instance method:
767 .. index::
768 object: class instance
769 object: instance
770 pair: class instance; call
771
772 The corresponding user-defined function is called, with an argument list that is
773 one longer than the argument list of the call: the instance becomes the first
774 argument.
775
776a class instance:
777 .. index::
778 pair: instance; call
779 single: __call__() (object method)
780
781 The class must define a :meth:`__call__` method; the effect is then the same as
782 if that method was called.
783
784
785.. _power:
786
787The power operator
788==================
789
790The power operator binds more tightly than unary operators on its left; it binds
791less tightly than unary operators on its right. The syntax is:
792
793.. productionlist::
794 power: `primary` ["**" `u_expr`]
795
796Thus, in an unparenthesized sequence of power and unary operators, the operators
797are evaluated from right to left (this does not constrain the evaluation order
Georg Brandlff457b12007-08-21 06:07:08 +0000798for the operands): ``-1**2`` results in ``-1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000799
800The power operator has the same semantics as the built-in :func:`pow` function,
801when called with two arguments: it yields its left argument raised to the power
802of its right argument. The numeric arguments are first converted to a common
803type. The result type is that of the arguments after coercion.
804
805With mixed operand types, the coercion rules for binary arithmetic operators
806apply. For int and long int operands, the result has the same type as the
807operands (after coercion) unless the second argument is negative; in that case,
808all arguments are converted to float and a float result is delivered. For
809example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last
810feature was added in Python 2.2. In Python 2.1 and before, if both arguments
811were of integer types and the second argument was negative, an exception was
812raised).
813
814Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000815Raising a negative number to a fractional power results in a :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000816
817
818.. _unary:
819
Georg Brandlec7d3902009-02-23 10:41:11 +0000820Unary arithmetic and bitwise operations
821=======================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000822
823.. index::
824 triple: unary; arithmetic; operation
Georg Brandlf725b952008-01-05 19:44:22 +0000825 triple: unary; bitwise; operation
Georg Brandl8ec7f652007-08-15 14:28:01 +0000826
Georg Brandlec7d3902009-02-23 10:41:11 +0000827All unary arithmetic and bitwise operations have the same priority:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000828
829.. productionlist::
830 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
831
832.. index::
833 single: negation
834 single: minus
835
836The unary ``-`` (minus) operator yields the negation of its numeric argument.
837
838.. index:: single: plus
839
840The unary ``+`` (plus) operator yields its numeric argument unchanged.
841
842.. index:: single: inversion
843
Georg Brandlf725b952008-01-05 19:44:22 +0000844The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
845long integer argument. The bitwise inversion of ``x`` is defined as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000846``-(x+1)``. It only applies to integral numbers.
847
848.. index:: exception: TypeError
849
850In all three cases, if the argument does not have the proper type, a
851:exc:`TypeError` exception is raised.
852
853
854.. _binary:
855
856Binary arithmetic operations
857============================
858
859.. index:: triple: binary; arithmetic; operation
860
861The binary arithmetic operations have the conventional priority levels. Note
862that some of these operations also apply to certain non-numeric types. Apart
863from the power operator, there are only two levels, one for multiplicative
864operators and one for additive operators:
865
866.. productionlist::
867 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
868 : | `m_expr` "%" `u_expr`
869 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
870
871.. index:: single: multiplication
872
873The ``*`` (multiplication) operator yields the product of its arguments. The
874arguments must either both be numbers, or one argument must be an integer (plain
875or long) and the other must be a sequence. In the former case, the numbers are
876converted to a common type and then multiplied together. In the latter case,
877sequence repetition is performed; a negative repetition factor yields an empty
878sequence.
879
880.. index::
881 exception: ZeroDivisionError
882 single: division
883
884The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
885their arguments. The numeric arguments are first converted to a common type.
886Plain or long integer division yields an integer of the same type; the result is
887that of mathematical division with the 'floor' function applied to the result.
888Division by zero raises the :exc:`ZeroDivisionError` exception.
889
890.. index:: single: modulo
891
892The ``%`` (modulo) operator yields the remainder from the division of the first
893argument by the second. The numeric arguments are first converted to a common
894type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
895arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
896(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
897result with the same sign as its second operand (or zero); the absolute value of
898the result is strictly smaller than the absolute value of the second operand
899[#]_.
900
901The integer division and modulo operators are connected by the following
902identity: ``x == (x/y)*y + (x%y)``. Integer division and modulo are also
903connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y,
904x%y)``. These identities don't hold for floating point numbers; there similar
905identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
906``floor(x/y) - 1`` [#]_.
907
908In addition to performing the modulo operation on numbers, the ``%`` operator is
909also overloaded by string and unicode objects to perform string formatting (also
910known as interpolation). The syntax for string formatting is described in the
911Python Library Reference, section :ref:`string-formatting`.
912
913.. deprecated:: 2.3
914 The floor division operator, the modulo operator, and the :func:`divmod`
915 function are no longer defined for complex numbers. Instead, convert to a
916 floating point number using the :func:`abs` function if appropriate.
917
918.. index:: single: addition
919
920The ``+`` (addition) operator yields the sum of its arguments. The arguments
921must either both be numbers or both sequences of the same type. In the former
922case, the numbers are converted to a common type and then added together. In
923the latter case, the sequences are concatenated.
924
925.. index:: single: subtraction
926
927The ``-`` (subtraction) operator yields the difference of its arguments. The
928numeric arguments are first converted to a common type.
929
930
931.. _shifting:
932
933Shifting operations
934===================
935
936.. index:: pair: shifting; operation
937
938The shifting operations have lower priority than the arithmetic operations:
939
940.. productionlist::
941 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
942
943These operators accept plain or long integers as arguments. The arguments are
944converted to a common type. They shift the first argument to the left or right
945by the number of bits given by the second argument.
946
947.. index:: exception: ValueError
948
Georg Brandle9135ba2008-05-11 10:55:59 +0000949A right shift by *n* bits is defined as division by ``pow(2, n)``. A left shift
950by *n* bits is defined as multiplication with ``pow(2, n)``. Negative shift
951counts raise a :exc:`ValueError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000952
953
954.. _bitwise:
955
Georg Brandlf725b952008-01-05 19:44:22 +0000956Binary bitwise operations
957=========================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000958
Georg Brandlf725b952008-01-05 19:44:22 +0000959.. index:: triple: binary; bitwise; operation
Georg Brandl8ec7f652007-08-15 14:28:01 +0000960
961Each of the three bitwise operations has a different priority level:
962
963.. productionlist::
964 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
965 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
966 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
967
Georg Brandlf725b952008-01-05 19:44:22 +0000968.. index:: pair: bitwise; and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000969
970The ``&`` operator yields the bitwise AND of its arguments, which must be plain
971or long integers. The arguments are converted to a common type.
972
973.. index::
Georg Brandlf725b952008-01-05 19:44:22 +0000974 pair: bitwise; xor
Georg Brandl8ec7f652007-08-15 14:28:01 +0000975 pair: exclusive; or
976
977The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
978must be plain or long integers. The arguments are converted to a common type.
979
980.. index::
Georg Brandlf725b952008-01-05 19:44:22 +0000981 pair: bitwise; or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000982 pair: inclusive; or
983
984The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
985must be plain or long integers. The arguments are converted to a common type.
986
987
988.. _comparisons:
Georg Brandlb19be572007-12-29 10:57:00 +0000989.. _is:
990.. _isnot:
991.. _in:
992.. _notin:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000993
994Comparisons
995===========
996
997.. index:: single: comparison
998
999.. index:: pair: C; language
1000
1001Unlike C, all comparison operations in Python have the same priority, which is
1002lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1003C, expressions like ``a < b < c`` have the interpretation that is conventional
1004in mathematics:
1005
1006.. productionlist::
1007 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1008 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
1009 : | "is" ["not"] | ["not"] "in"
1010
1011Comparisons yield boolean values: ``True`` or ``False``.
1012
1013.. index:: pair: chaining; comparisons
1014
1015Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1016``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1017cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1018
Georg Brandl32008322007-08-21 06:12:19 +00001019Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1020*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1021to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1022evaluated at most once.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001023
Georg Brandl32008322007-08-21 06:12:19 +00001024Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl8ec7f652007-08-15 14:28:01 +00001025*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1026pretty).
1027
1028The forms ``<>`` and ``!=`` are equivalent; for consistency with C, ``!=`` is
1029preferred; where ``!=`` is mentioned below ``<>`` is also accepted. The ``<>``
1030spelling is considered obsolescent.
1031
1032The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1033values of two objects. The objects need not have the same type. If both are
1034numbers, they are converted to a common type. Otherwise, objects of different
1035types *always* compare unequal, and are ordered consistently but arbitrarily.
Georg Brandl4ae4f872009-10-27 14:37:48 +00001036You can control comparison behavior of objects of non-built-in types by defining
Georg Brandl8ec7f652007-08-15 14:28:01 +00001037a ``__cmp__`` method or rich comparison methods like ``__gt__``, described in
1038section :ref:`specialnames`.
1039
1040(This unusual definition of comparison was used to simplify the definition of
1041operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
1042In the future, the comparison rules for objects of different types are likely to
1043change.)
1044
1045Comparison of objects of the same type depends on the type:
1046
1047* Numbers are compared arithmetically.
1048
1049* Strings are compared lexicographically using the numeric equivalents (the
1050 result of the built-in function :func:`ord`) of their characters. Unicode and
Mark Summerfield216ad332007-08-16 10:09:22 +00001051 8-bit strings are fully interoperable in this behavior. [#]_
Georg Brandl8ec7f652007-08-15 14:28:01 +00001052
1053* Tuples and lists are compared lexicographically using comparison of
1054 corresponding elements. This means that to compare equal, each element must
1055 compare equal and the two sequences must be of the same type and have the same
1056 length.
1057
1058 If not equal, the sequences are ordered the same as their first differing
1059 elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
1060 ``cmp(x,y)``. If the corresponding element does not exist, the shorter sequence
1061 is ordered first (for example, ``[1,2] < [1,2,3]``).
1062
1063* Mappings (dictionaries) compare equal if and only if their sorted (key, value)
1064 lists compare equal. [#]_ Outcomes other than equality are resolved
1065 consistently, but are not otherwise defined. [#]_
1066
Georg Brandl4ae4f872009-10-27 14:37:48 +00001067* Most other objects of built-in types compare unequal unless they are the same
Georg Brandl8ec7f652007-08-15 14:28:01 +00001068 object; the choice whether one object is considered smaller or larger than
1069 another one is made arbitrarily but consistently within one execution of a
1070 program.
1071
Georg Brandl5d2eb342009-10-27 15:08:27 +00001072.. _membership-test-details:
1073
Georg Brandl489343e2008-03-28 12:24:51 +00001074The operators :keyword:`in` and :keyword:`not in` test for collection
1075membership. ``x in s`` evaluates to true if *x* is a member of the collection
1076*s*, and false otherwise. ``x not in s`` returns the negation of ``x in s``.
1077The collection membership test has traditionally been bound to sequences; an
1078object is a member of a collection if the collection is a sequence and contains
1079an element equal to that object. However, it make sense for many other object
1080types to support membership tests without being a sequence. In particular,
1081dictionaries (for keys) and sets support membership testing.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001082
1083For the list and tuple types, ``x in y`` is true if and only if there exists an
1084index *i* such that ``x == y[i]`` is true.
1085
1086For the Unicode and string types, ``x in y`` is true if and only if *x* is a
1087substring of *y*. An equivalent test is ``y.find(x) != -1``. Note, *x* and *y*
1088need not be the same type; consequently, ``u'ab' in 'abc'`` will return
1089``True``. Empty strings are always considered to be a substring of any other
1090string, so ``"" in "abc"`` will return ``True``.
1091
1092.. versionchanged:: 2.3
1093 Previously, *x* was required to be a string of length ``1``.
1094
1095For user-defined classes which define the :meth:`__contains__` method, ``x in
1096y`` is true if and only if ``y.__contains__(x)`` is true.
1097
Georg Brandl5d2eb342009-10-27 15:08:27 +00001098For user-defined classes which do not define :meth:`__contains__` but do define
1099:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1100produced while iterating over ``y``. If an exception is raised during the
1101iteration, it is as if :keyword:`in` raised that exception.
1102
1103Lastly, the old-style iteration protocol is tried: if a class defines
Georg Brandl8ec7f652007-08-15 14:28:01 +00001104:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1105integer index *i* such that ``x == y[i]``, and all lower integer indices do not
1106raise :exc:`IndexError` exception. (If any other exception is raised, it is as
1107if :keyword:`in` raised that exception).
1108
1109.. index::
1110 operator: in
1111 operator: not in
1112 pair: membership; test
1113 object: sequence
1114
1115The operator :keyword:`not in` is defined to have the inverse true value of
1116:keyword:`in`.
1117
1118.. index::
1119 operator: is
1120 operator: is not
1121 pair: identity; test
1122
1123The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1124is 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 +00001125yields the inverse truth value. [#]_
Georg Brandl8ec7f652007-08-15 14:28:01 +00001126
1127
1128.. _booleans:
Georg Brandlb19be572007-12-29 10:57:00 +00001129.. _and:
1130.. _or:
1131.. _not:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001132
1133Boolean operations
1134==================
1135
1136.. index::
1137 pair: Conditional; expression
1138 pair: Boolean; operation
1139
Georg Brandl8ec7f652007-08-15 14:28:01 +00001140.. productionlist::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001141 or_test: `and_test` | `or_test` "or" `and_test`
1142 and_test: `not_test` | `and_test` "and" `not_test`
1143 not_test: `comparison` | "not" `not_test`
1144
1145In the context of Boolean operations, and also when expressions are used by
1146control flow statements, the following values are interpreted as false:
1147``False``, ``None``, numeric zero of all types, and empty strings and containers
1148(including strings, tuples, lists, dictionaries, sets and frozensets). All
Benjamin Petersonfe7c26d2008-09-23 13:32:46 +00001149other values are interpreted as true. (See the :meth:`~object.__nonzero__`
1150special method for a way to change this.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001151
1152.. index:: operator: not
1153
1154The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1155otherwise.
1156
Georg Brandl8ec7f652007-08-15 14:28:01 +00001157.. index:: operator: and
1158
1159The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1160returned; otherwise, *y* is evaluated and the resulting value is returned.
1161
1162.. index:: operator: or
1163
1164The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1165returned; otherwise, *y* is evaluated and the resulting value is returned.
1166
1167(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1168they return to ``False`` and ``True``, but rather return the last evaluated
1169argument. This is sometimes useful, e.g., if ``s`` is a string that should be
1170replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1171the desired value. Because :keyword:`not` has to invent a value anyway, it does
1172not bother to return a value of the same type as its argument, so e.g., ``not
1173'foo'`` yields ``False``, not ``''``.)
1174
1175
Georg Brandl5a7eca12010-03-21 19:29:04 +00001176Conditional Expressions
1177=======================
1178
1179.. versionadded:: 2.5
1180
1181.. index::
1182 pair: conditional; expression
1183 pair: ternary; operator
1184
1185.. productionlist::
1186 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1187 expression: `conditional_expression` | `lambda_form`
1188
1189Conditional expressions (sometimes called a "ternary operator") have the lowest
1190priority of all Python operations.
1191
1192The expression ``x if C else y`` first evaluates the condition, *C* (*not* *x*);
1193if *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
1194evaluated and its value is returned.
1195
1196See :pep:`308` for more details about conditional expressions.
1197
1198
Georg Brandl8ec7f652007-08-15 14:28:01 +00001199.. _lambdas:
Georg Brandl583bdc02009-04-28 18:11:53 +00001200.. _lambda:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001201
1202Lambdas
1203=======
1204
1205.. index::
1206 pair: lambda; expression
1207 pair: lambda; form
1208 pair: anonymous; function
1209
1210.. productionlist::
1211 lambda_form: "lambda" [`parameter_list`]: `expression`
1212 old_lambda_form: "lambda" [`parameter_list`]: `old_expression`
1213
1214Lambda forms (lambda expressions) have the same syntactic position as
1215expressions. They are a shorthand to create anonymous functions; the expression
1216``lambda arguments: expression`` yields a function object. The unnamed object
1217behaves like a function object defined with ::
1218
1219 def name(arguments):
1220 return expression
1221
1222See section :ref:`function` for the syntax of parameter lists. Note that
1223functions created with lambda forms cannot contain statements.
1224
Georg Brandl8ec7f652007-08-15 14:28:01 +00001225
1226.. _exprlists:
1227
1228Expression lists
1229================
1230
1231.. index:: pair: expression; list
1232
1233.. productionlist::
1234 expression_list: `expression` ( "," `expression` )* [","]
1235
1236.. index:: object: tuple
1237
1238An expression list containing at least one comma yields a tuple. The length of
1239the tuple is the number of expressions in the list. The expressions are
1240evaluated from left to right.
1241
1242.. index:: pair: trailing; comma
1243
1244The trailing comma is required only to create a single tuple (a.k.a. a
1245*singleton*); it is optional in all other cases. A single expression without a
1246trailing comma doesn't create a tuple, but rather yields the value of that
1247expression. (To create an empty tuple, use an empty pair of parentheses:
1248``()``.)
1249
1250
1251.. _evalorder:
1252
1253Evaluation order
1254================
1255
1256.. index:: pair: evaluation; order
1257
1258Python evaluates expressions from left to right. Notice that while evaluating an
1259assignment, the right-hand side is evaluated before the left-hand side.
1260
1261In the following lines, expressions will be evaluated in the arithmetic order of
1262their suffixes::
1263
1264 expr1, expr2, expr3, expr4
1265 (expr1, expr2, expr3, expr4)
1266 {expr1: expr2, expr3: expr4}
1267 expr1 + expr2 * (expr3 - expr4)
Georg Brandl463f39d2008-08-08 06:42:20 +00001268 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001269 expr3, expr4 = expr1, expr2
1270
1271
1272.. _operator-summary:
1273
1274Summary
1275=======
1276
1277.. index:: pair: operator; precedence
1278
1279The following table summarizes the operator precedences in Python, from lowest
1280precedence (least binding) to highest precedence (most binding). Operators in
1281the same box have the same precedence. Unless the syntax is explicitly given,
1282operators are binary. Operators in the same box group left to right (except for
1283comparisons, including tests, which all have the same precedence and chain from
1284left to right --- see section :ref:`comparisons` --- and exponentiation, which
1285groups from right to left).
1286
1287+-----------------------------------------------+-------------------------------------+
1288| Operator | Description |
1289+===============================================+=====================================+
1290| :keyword:`lambda` | Lambda expression |
1291+-----------------------------------------------+-------------------------------------+
Georg Brandl5a7eca12010-03-21 19:29:04 +00001292| :keyword:`if` -- :keyword:`else` | Conditional expression |
1293+-----------------------------------------------+-------------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001294| :keyword:`or` | Boolean OR |
1295+-----------------------------------------------+-------------------------------------+
1296| :keyword:`and` | Boolean AND |
1297+-----------------------------------------------+-------------------------------------+
1298| :keyword:`not` *x* | Boolean NOT |
1299+-----------------------------------------------+-------------------------------------+
Georg Brandlec7d3902009-02-23 10:41:11 +00001300| :keyword:`in`, :keyword:`not` :keyword:`in`, | Comparisons, including membership |
1301| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests, |
1302| ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==`` | |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001303+-----------------------------------------------+-------------------------------------+
1304| ``|`` | Bitwise OR |
1305+-----------------------------------------------+-------------------------------------+
1306| ``^`` | Bitwise XOR |
1307+-----------------------------------------------+-------------------------------------+
1308| ``&`` | Bitwise AND |
1309+-----------------------------------------------+-------------------------------------+
1310| ``<<``, ``>>`` | Shifts |
1311+-----------------------------------------------+-------------------------------------+
1312| ``+``, ``-`` | Addition and subtraction |
1313+-----------------------------------------------+-------------------------------------+
Georg Brandlec7d3902009-02-23 10:41:11 +00001314| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001315+-----------------------------------------------+-------------------------------------+
Georg Brandlec7d3902009-02-23 10:41:11 +00001316| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001317+-----------------------------------------------+-------------------------------------+
Georg Brandlec7d3902009-02-23 10:41:11 +00001318| ``**`` | Exponentiation [#]_ |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001319+-----------------------------------------------+-------------------------------------+
Georg Brandlec7d3902009-02-23 10:41:11 +00001320| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1321| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001322+-----------------------------------------------+-------------------------------------+
Georg Brandlec7d3902009-02-23 10:41:11 +00001323| ``(expressions...)``, | Binding or tuple display, |
1324| ``[expressions...]``, | list display, |
1325| ``{key:datum...}``, | dictionary display, |
1326| ```expressions...``` | string conversion |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001327+-----------------------------------------------+-------------------------------------+
1328
1329.. rubric:: Footnotes
1330
Martin v. Löwis0b667312008-05-23 19:33:13 +00001331.. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control
Georg Brandl734373c2009-01-03 21:55:17 +00001332 variables of each ``for`` it contains into the containing scope. However, this
Martin v. Löwis0b667312008-05-23 19:33:13 +00001333 behavior is deprecated, and relying on it will not work in Python 3.0
Georg Brandl8ec7f652007-08-15 14:28:01 +00001334
1335.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1336 true numerically due to roundoff. For example, and assuming a platform on which
1337 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1338 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1339 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod`
1340 in the :mod:`math` module returns a result whose sign matches the sign of the
1341 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1342 is more appropriate depends on the application.
1343
1344.. [#] If x is very close to an exact integer multiple of y, it's possible for
1345 ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding. In such
1346 cases, Python returns the latter result, in order to preserve that
1347 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1348
Mark Summerfield216ad332007-08-16 10:09:22 +00001349.. [#] While comparisons between unicode strings make sense at the byte
1350 level, they may be counter-intuitive to users. For example, the
Mark Summerfieldd92e8712007-10-03 08:53:21 +00001351 strings ``u"\u00C7"`` and ``u"\u0043\u0327"`` compare differently,
Mark Summerfield216ad332007-08-16 10:09:22 +00001352 even though they both represent the same unicode character (LATIN
Ezio Melotti8d837ab2010-04-02 22:13:35 +00001353 CAPITAL LETTER C WITH CEDILLA). To compare strings in a human
Mark Summerfieldd92e8712007-10-03 08:53:21 +00001354 recognizable way, compare using :func:`unicodedata.normalize`.
Mark Summerfield216ad332007-08-16 10:09:22 +00001355
Georg Brandl8ec7f652007-08-15 14:28:01 +00001356.. [#] The implementation computes this efficiently, without constructing lists or
1357 sorting.
1358
1359.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
1360 value) lists, but this was very expensive for the common case of comparing for
1361 equality. An even earlier version of Python compared dictionaries by identity
1362 only, but this caused surprises because people expected to be able to test a
1363 dictionary for emptiness by comparing it to ``{}``.
1364
Georg Brandl734373c2009-01-03 21:55:17 +00001365.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Georg Brandl3214a012008-07-01 20:50:02 +00001366 descriptors, you may notice seemingly unusual behaviour in certain uses of
1367 the :keyword:`is` operator, like those involving comparisons between instance
1368 methods, or constants. Check their documentation for more info.
Georg Brandlec7d3902009-02-23 10:41:11 +00001369
1370.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1371 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.