blob: 93eb4122df3819338b32bbeb3173fb779c277ddf [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
108.. %
109.. %
110
111
112.. _atom-literals:
113
114Literals
115--------
116
117.. index:: single: literal
118
119Python supports string literals and various numeric literals:
120
121.. productionlist::
122 literal: `stringliteral` | `integer` | `longinteger`
123 : | `floatnumber` | `imagnumber`
124
125Evaluation of a literal yields an object of the given type (string, integer,
126long integer, floating point number, complex number) with the given value. The
127value may be approximated in the case of floating point and imaginary (complex)
128literals. See section :ref:`literals` for details.
129
130.. index::
131 triple: immutable; data; type
132 pair: immutable; object
133
134All literals correspond to immutable data types, and hence the object's identity
135is less important than its value. Multiple evaluations of literals with the
136same value (either the same occurrence in the program text or a different
137occurrence) may obtain the same object or a different object with the same
138value.
139
140
141.. _parenthesized:
142
143Parenthesized forms
144-------------------
145
146.. index:: single: parenthesized form
147
148A parenthesized form is an optional expression list enclosed in parentheses:
149
150.. productionlist::
151 parenth_form: "(" [`expression_list`] ")"
152
153A parenthesized expression list yields whatever that expression list yields: if
154the list contains at least one comma, it yields a tuple; otherwise, it yields
155the single expression that makes up the expression list.
156
157.. index:: pair: empty; tuple
158
159An empty pair of parentheses yields an empty tuple object. Since tuples are
160immutable, the rules for literals apply (i.e., two occurrences of the empty
161tuple may or may not yield the same object).
162
163.. index::
164 single: comma
165 pair: tuple; display
166
167Note that tuples are not formed by the parentheses, but rather by use of the
168comma operator. The exception is the empty tuple, for which parentheses *are*
169required --- allowing unparenthesized "nothing" in expressions would cause
170ambiguities and allow common typos to pass uncaught.
171
172
173.. _lists:
174
175List displays
176-------------
177
178.. index::
179 pair: list; display
180 pair: list; comprehensions
181
182A list display is a possibly empty series of expressions enclosed in square
183brackets:
184
185.. productionlist::
186 list_display: "[" [`expression_list` | `list_comprehension`] "]"
187 list_comprehension: `expression` `list_for`
188 list_for: "for" `target_list` "in" `old_expression_list` [`list_iter`]
189 old_expression_list: `old_expression` [("," `old_expression`)+ [","]]
190 list_iter: `list_for` | `list_if`
191 list_if: "if" `old_expression` [`list_iter`]
192
193.. index::
194 pair: list; comprehensions
195 object: list
196 pair: empty; list
197
198A list display yields a new list object. Its contents are specified by
199providing either a list of expressions or a list comprehension. When a
200comma-separated list of expressions is supplied, its elements are evaluated from
201left to right and placed into the list object in that order. When a list
202comprehension is supplied, it consists of a single expression followed by at
203least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if`
204clauses. In this case, the elements of the new list are those that would be
205produced by considering each of the :keyword:`for` or :keyword:`if` clauses a
206block, nesting from left to right, and evaluating the expression to produce a
207list element each time the innermost block is reached [#]_.
208
209
210.. _genexpr:
211
212Generator expressions
213---------------------
214
215.. index:: pair: generator; expression
216
217A generator expression is a compact generator notation in parentheses:
218
219.. productionlist::
220 generator_expression: "(" `expression` `genexpr_for` ")"
221 genexpr_for: "for" `target_list` "in" `or_test` [`genexpr_iter`]
222 genexpr_iter: `genexpr_for` | `genexpr_if`
223 genexpr_if: "if" `old_expression` [`genexpr_iter`]
224
225.. index:: object: generator
226
227A generator expression yields a new generator object. It consists of a single
228expression followed by at least one :keyword:`for` clause and zero or more
229:keyword:`for` or :keyword:`if` clauses. The iterating values of the new
230generator are those that would be produced by considering each of the
231:keyword:`for` or :keyword:`if` clauses a block, nesting from left to right, and
232evaluating the expression to yield a value that is reached the innermost block
233for each iteration.
234
235Variables used in the generator expression are evaluated lazily when the
236:meth:`next` method is called for generator object (in the same fashion as
237normal generators). However, the leftmost :keyword:`for` clause is immediately
238evaluated so that error produced by it can be seen before any other possible
239error in the code that handles the generator expression. Subsequent
240:keyword:`for` clauses cannot be evaluated immediately since they may depend on
241the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y
242in bar(x))``.
243
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
279:ref:`types`. (To summarize, the key type should be hashable, which excludes
280all 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
400 :keyword:`yield` expression that could receieve the value.
401
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)
433 ... except GeneratorExit:
434 ... # never catch GeneratorExit
435 ... raise
436 ... except Exception, e:
437 ... value = e
438 ... finally:
439 ... print "Don't forget to clean up when 'close()' is called."
440 ...
441 >>> generator = echo(1)
442 >>> print generator.next()
443 Execution starts when 'next()' is called for the first time.
444 1
445 >>> print generator.next()
446 None
447 >>> print generator.send(2)
448 2
449 >>> generator.throw(TypeError, "spam")
450 TypeError('spam',)
451 >>> generator.close()
452 Don't forget to clean up when 'close()' is called.
453
454
455.. seealso::
456
457 :pep:`0342` - Coroutines via Enhanced Generators
458 The proposal to enhance the API and syntax of generators, making them usable as
459 simple coroutines.
460
461
462.. _primaries:
463
464Primaries
465=========
466
467.. index:: single: primary
468
469Primaries represent the most tightly bound operations of the language. Their
470syntax is:
471
472.. productionlist::
473 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
474
475
476.. _attribute-references:
477
478Attribute references
479--------------------
480
481.. index:: pair: attribute; reference
482
483An attribute reference is a primary followed by a period and a name:
484
485.. productionlist::
486 attributeref: `primary` "." `identifier`
487
488.. index::
489 exception: AttributeError
490 object: module
491 object: list
492
493The primary must evaluate to an object of a type that supports attribute
494references, e.g., a module, list, or an instance. This object is then asked to
495produce the attribute whose name is the identifier. If this attribute is not
496available, the exception :exc:`AttributeError` is raised. Otherwise, the type
497and value of the object produced is determined by the object. Multiple
498evaluations of the same attribute reference may yield different objects.
499
500
501.. _subscriptions:
502
503Subscriptions
504-------------
505
506.. index:: single: subscription
507
508.. index::
509 object: sequence
510 object: mapping
511 object: string
512 object: tuple
513 object: list
514 object: dictionary
515 pair: sequence; item
516
517A subscription selects an item of a sequence (string, tuple or list) or mapping
518(dictionary) object:
519
520.. productionlist::
521 subscription: `primary` "[" `expression_list` "]"
522
523The primary must evaluate to an object of a sequence or mapping type.
524
525If the primary is a mapping, the expression list must evaluate to an object
526whose value is one of the keys of the mapping, and the subscription selects the
527value in the mapping that corresponds to that key. (The expression list is a
528tuple except if it has exactly one item.)
529
530If the primary is a sequence, the expression (list) must evaluate to a plain
531integer. If this value is negative, the length of the sequence is added to it
532(so that, e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value
533must be a nonnegative integer less than the number of items in the sequence, and
534the subscription selects the item whose index is that value (counting from
535zero).
536
537.. index::
538 single: character
539 pair: string; item
540
541A string's items are characters. A character is not a separate data type but a
542string of exactly one character.
543
544
545.. _slicings:
546
547Slicings
548--------
549
550.. index::
551 single: slicing
552 single: slice
553
554.. index::
555 object: sequence
556 object: string
557 object: tuple
558 object: list
559
560A slicing selects a range of items in a sequence object (e.g., a string, tuple
561or list). Slicings may be used as expressions or as targets in assignment or
562:keyword:`del` statements. The syntax for a slicing:
563
564.. productionlist::
565 slicing: `simple_slicing` | `extended_slicing`
566 simple_slicing: `primary` "[" `short_slice` "]"
567 extended_slicing: `primary` "[" `slice_list` "]"
568 slice_list: `slice_item` ("," `slice_item`)* [","]
569 slice_item: `expression` | `proper_slice` | `ellipsis`
570 proper_slice: `short_slice` | `long_slice`
571 short_slice: [`lower_bound`] ":" [`upper_bound`]
572 long_slice: `short_slice` ":" [`stride`]
573 lower_bound: `expression`
574 upper_bound: `expression`
575 stride: `expression`
576 ellipsis: "..."
577
578.. index:: pair: extended; slicing
579
580There is ambiguity in the formal syntax here: anything that looks like an
581expression list also looks like a slice list, so any subscription can be
582interpreted as a slicing. Rather than further complicating the syntax, this is
583disambiguated by defining that in this case the interpretation as a subscription
584takes priority over the interpretation as a slicing (this is the case if the
585slice list contains no proper slice nor ellipses). Similarly, when the slice
586list has exactly one short slice and no trailing comma, the interpretation as a
587simple slicing takes priority over that as an extended slicing.
588
589The semantics for a simple slicing are as follows. The primary must evaluate to
590a sequence object. The lower and upper bound expressions, if present, must
591evaluate to plain integers; defaults are zero and the ``sys.maxint``,
592respectively. If either bound is negative, the sequence's length is added to
593it. The slicing now selects all items with index *k* such that ``i <= k < j``
594where *i* and *j* are the specified lower and upper bounds. This may be an
595empty sequence. It is not an error if *i* or *j* lie outside the range of valid
596indexes (such items don't exist so they aren't selected).
597
598.. index::
599 single: start (slice object attribute)
600 single: stop (slice object attribute)
601 single: step (slice object attribute)
602
603The semantics for an extended slicing are as follows. The primary must evaluate
604to a mapping object, and it is indexed with a key that is constructed from the
605slice list, as follows. If the slice list contains at least one comma, the key
606is a tuple containing the conversion of the slice items; otherwise, the
607conversion of the lone slice item is the key. The conversion of a slice item
608that is an expression is that expression. The conversion of an ellipsis slice
609item is the built-in ``Ellipsis`` object. The conversion of a proper slice is a
610slice object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
611:attr:`step` attributes are the values of the expressions given as lower bound,
612upper bound and stride, respectively, substituting ``None`` for missing
613expressions.
614
615
616.. _calls:
617
618Calls
619-----
620
621.. index:: single: call
622
623.. index:: object: callable
624
625A call calls a callable object (e.g., a function) with a possibly empty series
626of arguments:
627
628.. productionlist::
629 call: `primary` "(" [`argument_list` [","]
630 : | `expression` `genexpr_for`] ")"
631 argument_list: `positional_arguments` ["," `keyword_arguments`]
632 : ["," "*" `expression`]
633 : ["," "**" `expression`]
634 : | `keyword_arguments` ["," "*" `expression`]
635 : ["," "**" `expression`]
636 : | "*" `expression` ["," "**" `expression`]
637 : | "**" `expression`
638 positional_arguments: `expression` ("," `expression`)*
639 keyword_arguments: `keyword_item` ("," `keyword_item`)*
640 keyword_item: `identifier` "=" `expression`
641
642A trailing comma may be present after the positional and keyword arguments but
643does not affect the semantics.
644
645The primary must evaluate to a callable object (user-defined functions, built-in
646functions, methods of built-in objects, class objects, methods of class
647instances, and certain class instances themselves are callable; extensions may
648define additional callable object types). All argument expressions are
649evaluated before the call is attempted. Please refer to section :ref:`function`
650for the syntax of formal parameter lists.
651
652If keyword arguments are present, they are first converted to positional
653arguments, as follows. First, a list of unfilled slots is created for the
654formal parameters. If there are N positional arguments, they are placed in the
655first N slots. Next, for each keyword argument, the identifier is used to
656determine the corresponding slot (if the identifier is the same as the first
657formal parameter name, the first slot is used, and so on). If the slot is
658already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
659the argument is placed in the slot, filling it (even if the expression is
660``None``, it fills the slot). When all arguments have been processed, the slots
661that are still unfilled are filled with the corresponding default value from the
662function definition. (Default values are calculated, once, when the function is
663defined; thus, a mutable object such as a list or dictionary used as default
664value will be shared by all calls that don't specify an argument value for the
665corresponding slot; this should usually be avoided.) If there are any unfilled
666slots for which no default value is specified, a :exc:`TypeError` exception is
667raised. Otherwise, the list of filled slots is used as the argument list for
668the call.
669
670If there are more positional arguments than there are formal parameter slots, a
671:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
672``*identifier`` is present; in this case, that formal parameter receives a tuple
673containing the excess positional arguments (or an empty tuple if there were no
674excess positional arguments).
675
676If any keyword argument does not correspond to a formal parameter name, a
677:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
678``**identifier`` is present; in this case, that formal parameter receives a
679dictionary containing the excess keyword arguments (using the keywords as keys
680and the argument values as corresponding values), or a (new) empty dictionary if
681there were no excess keyword arguments.
682
683If the syntax ``*expression`` appears in the function call, ``expression`` must
684evaluate to a sequence. Elements from this sequence are treated as if they were
685additional positional arguments; if there are postional arguments *x1*,...,*xN*
686, and ``expression`` evaluates to a sequence *y1*,...,*yM*, this is equivalent
687to a call with M+N positional arguments *x1*,...,*xN*,*y1*,...,*yM*.
688
689A consequence of this is that although the ``*expression`` syntax appears
690*after* any keyword arguments, it is processed *before* the keyword arguments
691(and the ``**expression`` argument, if any -- see below). So::
692
693 >>> def f(a, b):
694 ... print a, b
695 ...
696 >>> f(b=1, *(2,))
697 2 1
698 >>> f(a=1, *(2,))
699 Traceback (most recent call last):
700 File "<stdin>", line 1, in ?
701 TypeError: f() got multiple values for keyword argument 'a'
702 >>> f(1, *(2,))
703 1 2
704
705It is unusual for both keyword arguments and the ``*expression`` syntax to be
706used in the same call, so in practice this confusion does not arise.
707
708If the syntax ``**expression`` appears in the function call, ``expression`` must
709evaluate to a mapping, the contents of which are treated as additional keyword
710arguments. In the case of a keyword appearing in both ``expression`` and as an
711explicit keyword argument, a :exc:`TypeError` exception is raised.
712
713Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
714used as positional argument slots or as keyword argument names. Formal
715parameters using the syntax ``(sublist)`` cannot be used as keyword argument
716names; the outermost sublist corresponds to a single unnamed argument slot, and
717the argument value is assigned to the sublist using the usual tuple assignment
718rules after all other parameter processing is done.
719
720A call always returns some value, possibly ``None``, unless it raises an
721exception. How this value is computed depends on the type of the callable
722object.
723
724If it is---
725
726a user-defined function:
727 .. index::
728 pair: function; call
729 triple: user-defined; function; call
730 object: user-defined function
731 object: function
732
733 The code block for the function is executed, passing it the argument list. The
734 first thing the code block will do is bind the formal parameters to the
735 arguments; this is described in section :ref:`function`. When the code block
736 executes a :keyword:`return` statement, this specifies the return value of the
737 function call.
738
739a built-in function or method:
740 .. index::
741 pair: function; call
742 pair: built-in function; call
743 pair: method; call
744 pair: built-in method; call
745 object: built-in method
746 object: built-in function
747 object: method
748 object: function
749
750 The result is up to the interpreter; see :ref:`built-in-funcs` for the
751 descriptions of built-in functions and methods.
752
753a class object:
754 .. index::
755 object: class
756 pair: class object; call
757
758 A new instance of that class is returned.
759
760a class instance method:
761 .. index::
762 object: class instance
763 object: instance
764 pair: class instance; call
765
766 The corresponding user-defined function is called, with an argument list that is
767 one longer than the argument list of the call: the instance becomes the first
768 argument.
769
770a class instance:
771 .. index::
772 pair: instance; call
773 single: __call__() (object method)
774
775 The class must define a :meth:`__call__` method; the effect is then the same as
776 if that method was called.
777
778
779.. _power:
780
781The power operator
782==================
783
784The power operator binds more tightly than unary operators on its left; it binds
785less tightly than unary operators on its right. The syntax is:
786
787.. productionlist::
788 power: `primary` ["**" `u_expr`]
789
790Thus, in an unparenthesized sequence of power and unary operators, the operators
791are evaluated from right to left (this does not constrain the evaluation order
Georg Brandlff457b12007-08-21 06:07:08 +0000792for the operands): ``-1**2`` results in ``-1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000793
794The power operator has the same semantics as the built-in :func:`pow` function,
795when called with two arguments: it yields its left argument raised to the power
796of its right argument. The numeric arguments are first converted to a common
797type. The result type is that of the arguments after coercion.
798
799With mixed operand types, the coercion rules for binary arithmetic operators
800apply. For int and long int operands, the result has the same type as the
801operands (after coercion) unless the second argument is negative; in that case,
802all arguments are converted to float and a float result is delivered. For
803example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last
804feature was added in Python 2.2. In Python 2.1 and before, if both arguments
805were of integer types and the second argument was negative, an exception was
806raised).
807
808Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
809Raising a negative number to a fractional power results in a :exc:`ValueError`.
810
811
812.. _unary:
813
814Unary arithmetic operations
815===========================
816
817.. index::
818 triple: unary; arithmetic; operation
819 triple: unary; bit-wise; operation
820
821All unary arithmetic (and bit-wise) operations have the same priority:
822
823.. productionlist::
824 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
825
826.. index::
827 single: negation
828 single: minus
829
830The unary ``-`` (minus) operator yields the negation of its numeric argument.
831
832.. index:: single: plus
833
834The unary ``+`` (plus) operator yields its numeric argument unchanged.
835
836.. index:: single: inversion
837
838The unary ``~`` (invert) operator yields the bit-wise inversion of its plain or
839long integer argument. The bit-wise inversion of ``x`` is defined as
840``-(x+1)``. It only applies to integral numbers.
841
842.. index:: exception: TypeError
843
844In all three cases, if the argument does not have the proper type, a
845:exc:`TypeError` exception is raised.
846
847
848.. _binary:
849
850Binary arithmetic operations
851============================
852
853.. index:: triple: binary; arithmetic; operation
854
855The binary arithmetic operations have the conventional priority levels. Note
856that some of these operations also apply to certain non-numeric types. Apart
857from the power operator, there are only two levels, one for multiplicative
858operators and one for additive operators:
859
860.. productionlist::
861 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
862 : | `m_expr` "%" `u_expr`
863 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
864
865.. index:: single: multiplication
866
867The ``*`` (multiplication) operator yields the product of its arguments. The
868arguments must either both be numbers, or one argument must be an integer (plain
869or long) and the other must be a sequence. In the former case, the numbers are
870converted to a common type and then multiplied together. In the latter case,
871sequence repetition is performed; a negative repetition factor yields an empty
872sequence.
873
874.. index::
875 exception: ZeroDivisionError
876 single: division
877
878The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
879their arguments. The numeric arguments are first converted to a common type.
880Plain or long integer division yields an integer of the same type; the result is
881that of mathematical division with the 'floor' function applied to the result.
882Division by zero raises the :exc:`ZeroDivisionError` exception.
883
884.. index:: single: modulo
885
886The ``%`` (modulo) operator yields the remainder from the division of the first
887argument by the second. The numeric arguments are first converted to a common
888type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
889arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
890(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
891result with the same sign as its second operand (or zero); the absolute value of
892the result is strictly smaller than the absolute value of the second operand
893[#]_.
894
895The integer division and modulo operators are connected by the following
896identity: ``x == (x/y)*y + (x%y)``. Integer division and modulo are also
897connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y,
898x%y)``. These identities don't hold for floating point numbers; there similar
899identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
900``floor(x/y) - 1`` [#]_.
901
902In addition to performing the modulo operation on numbers, the ``%`` operator is
903also overloaded by string and unicode objects to perform string formatting (also
904known as interpolation). The syntax for string formatting is described in the
905Python Library Reference, section :ref:`string-formatting`.
906
907.. deprecated:: 2.3
908 The floor division operator, the modulo operator, and the :func:`divmod`
909 function are no longer defined for complex numbers. Instead, convert to a
910 floating point number using the :func:`abs` function if appropriate.
911
912.. index:: single: addition
913
914The ``+`` (addition) operator yields the sum of its arguments. The arguments
915must either both be numbers or both sequences of the same type. In the former
916case, the numbers are converted to a common type and then added together. In
917the latter case, the sequences are concatenated.
918
919.. index:: single: subtraction
920
921The ``-`` (subtraction) operator yields the difference of its arguments. The
922numeric arguments are first converted to a common type.
923
924
925.. _shifting:
926
927Shifting operations
928===================
929
930.. index:: pair: shifting; operation
931
932The shifting operations have lower priority than the arithmetic operations:
933
934.. productionlist::
935 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
936
937These operators accept plain or long integers as arguments. The arguments are
938converted to a common type. They shift the first argument to the left or right
939by the number of bits given by the second argument.
940
941.. index:: exception: ValueError
942
943A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift
944by *n* bits is defined as multiplication with ``pow(2,n)``; for plain integers
945there is no overflow check so in that case the operation drops bits and flips
946the sign if the result is not less than ``pow(2,31)`` in absolute value.
947Negative shift counts raise a :exc:`ValueError` exception.
948
949
950.. _bitwise:
951
952Binary bit-wise operations
953==========================
954
955.. index:: triple: binary; bit-wise; operation
956
957Each of the three bitwise operations has a different priority level:
958
959.. productionlist::
960 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
961 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
962 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
963
964.. index:: pair: bit-wise; and
965
966The ``&`` operator yields the bitwise AND of its arguments, which must be plain
967or long integers. The arguments are converted to a common type.
968
969.. index::
970 pair: bit-wise; xor
971 pair: exclusive; or
972
973The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
974must be plain or long integers. The arguments are converted to a common type.
975
976.. index::
977 pair: bit-wise; or
978 pair: inclusive; or
979
980The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
981must be plain or long integers. The arguments are converted to a common type.
982
983
984.. _comparisons:
985
986Comparisons
987===========
988
989.. index:: single: comparison
990
991.. index:: pair: C; language
992
993Unlike C, all comparison operations in Python have the same priority, which is
994lower than that of any arithmetic, shifting or bitwise operation. Also unlike
995C, expressions like ``a < b < c`` have the interpretation that is conventional
996in mathematics:
997
998.. productionlist::
999 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1000 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
1001 : | "is" ["not"] | ["not"] "in"
1002
1003Comparisons yield boolean values: ``True`` or ``False``.
1004
1005.. index:: pair: chaining; comparisons
1006
1007Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1008``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1009cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1010
1011Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *opa*, *opb*, ...,
1012*opy* are comparison operators, then *a opa b opb c* ...*y opy z* is equivalent
1013to *a opa b* :keyword:`and` *b opb c* :keyword:`and` ... *y opy z*, except that
1014each expression is evaluated at most once.
1015
1016Note that *a opa b opb c* doesn't imply any kind of comparison between *a* and
1017*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1018pretty).
1019
1020The forms ``<>`` and ``!=`` are equivalent; for consistency with C, ``!=`` is
1021preferred; where ``!=`` is mentioned below ``<>`` is also accepted. The ``<>``
1022spelling is considered obsolescent.
1023
1024The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1025values of two objects. The objects need not have the same type. If both are
1026numbers, they are converted to a common type. Otherwise, objects of different
1027types *always* compare unequal, and are ordered consistently but arbitrarily.
1028You can control comparison behavior of objects of non-builtin types by defining
1029a ``__cmp__`` method or rich comparison methods like ``__gt__``, described in
1030section :ref:`specialnames`.
1031
1032(This unusual definition of comparison was used to simplify the definition of
1033operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
1034In the future, the comparison rules for objects of different types are likely to
1035change.)
1036
1037Comparison of objects of the same type depends on the type:
1038
1039* Numbers are compared arithmetically.
1040
1041* Strings are compared lexicographically using the numeric equivalents (the
1042 result of the built-in function :func:`ord`) of their characters. Unicode and
Mark Summerfield216ad332007-08-16 10:09:22 +00001043 8-bit strings are fully interoperable in this behavior. [#]_
Georg Brandl8ec7f652007-08-15 14:28:01 +00001044
1045* Tuples and lists are compared lexicographically using comparison of
1046 corresponding elements. This means that to compare equal, each element must
1047 compare equal and the two sequences must be of the same type and have the same
1048 length.
1049
1050 If not equal, the sequences are ordered the same as their first differing
1051 elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
1052 ``cmp(x,y)``. If the corresponding element does not exist, the shorter sequence
1053 is ordered first (for example, ``[1,2] < [1,2,3]``).
1054
1055* Mappings (dictionaries) compare equal if and only if their sorted (key, value)
1056 lists compare equal. [#]_ Outcomes other than equality are resolved
1057 consistently, but are not otherwise defined. [#]_
1058
1059* Most other objects of builtin types compare unequal unless they are the same
1060 object; the choice whether one object is considered smaller or larger than
1061 another one is made arbitrarily but consistently within one execution of a
1062 program.
1063
1064The operators :keyword:`in` and :keyword:`not in` test for set membership. ``x
1065in s`` evaluates to true if *x* is a member of the set *s*, and false otherwise.
1066``x not in s`` returns the negation of ``x in s``. The set membership test has
1067traditionally been bound to sequences; an object is a member of a set if the set
1068is a sequence and contains an element equal to that object. However, it is
1069possible for an object to support membership tests without being a sequence. In
1070particular, dictionaries support membership testing as a nicer way of spelling
1071``key in dict``; other mapping types may follow suit.
1072
1073For the list and tuple types, ``x in y`` is true if and only if there exists an
1074index *i* such that ``x == y[i]`` is true.
1075
1076For the Unicode and string types, ``x in y`` is true if and only if *x* is a
1077substring of *y*. An equivalent test is ``y.find(x) != -1``. Note, *x* and *y*
1078need not be the same type; consequently, ``u'ab' in 'abc'`` will return
1079``True``. Empty strings are always considered to be a substring of any other
1080string, so ``"" in "abc"`` will return ``True``.
1081
1082.. versionchanged:: 2.3
1083 Previously, *x* was required to be a string of length ``1``.
1084
1085For user-defined classes which define the :meth:`__contains__` method, ``x in
1086y`` is true if and only if ``y.__contains__(x)`` is true.
1087
1088For user-defined classes which do not define :meth:`__contains__` and do define
1089:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1090integer index *i* such that ``x == y[i]``, and all lower integer indices do not
1091raise :exc:`IndexError` exception. (If any other exception is raised, it is as
1092if :keyword:`in` raised that exception).
1093
1094.. index::
1095 operator: in
1096 operator: not in
1097 pair: membership; test
1098 object: sequence
1099
1100The operator :keyword:`not in` is defined to have the inverse true value of
1101:keyword:`in`.
1102
1103.. index::
1104 operator: is
1105 operator: is not
1106 pair: identity; test
1107
1108The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1109is y`` is true if and only if *x* and *y* are the same object. ``x is not y``
1110yields the inverse truth value.
1111
1112
1113.. _booleans:
1114
1115Boolean operations
1116==================
1117
1118.. index::
1119 pair: Conditional; expression
1120 pair: Boolean; operation
1121
1122Boolean operations have the lowest priority of all Python operations:
1123
1124.. productionlist::
1125 expression: `conditional_expression` | `lambda_form`
1126 old_expression: `or_test` | `old_lambda_form`
1127 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1128 or_test: `and_test` | `or_test` "or" `and_test`
1129 and_test: `not_test` | `and_test` "and" `not_test`
1130 not_test: `comparison` | "not" `not_test`
1131
1132In the context of Boolean operations, and also when expressions are used by
1133control flow statements, the following values are interpreted as false:
1134``False``, ``None``, numeric zero of all types, and empty strings and containers
1135(including strings, tuples, lists, dictionaries, sets and frozensets). All
1136other values are interpreted as true.
1137
1138.. index:: operator: not
1139
1140The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1141otherwise.
1142
1143The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is
1144true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated
1145and its value is returned.
1146
1147.. versionadded:: 2.5
1148
1149.. index:: operator: and
1150
1151The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1152returned; otherwise, *y* is evaluated and the resulting value is returned.
1153
1154.. index:: operator: or
1155
1156The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1157returned; otherwise, *y* is evaluated and the resulting value is returned.
1158
1159(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1160they return to ``False`` and ``True``, but rather return the last evaluated
1161argument. This is sometimes useful, e.g., if ``s`` is a string that should be
1162replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1163the desired value. Because :keyword:`not` has to invent a value anyway, it does
1164not bother to return a value of the same type as its argument, so e.g., ``not
1165'foo'`` yields ``False``, not ``''``.)
1166
1167
1168.. _lambdas:
1169
1170Lambdas
1171=======
1172
1173.. index::
1174 pair: lambda; expression
1175 pair: lambda; form
1176 pair: anonymous; function
1177
1178.. productionlist::
1179 lambda_form: "lambda" [`parameter_list`]: `expression`
1180 old_lambda_form: "lambda" [`parameter_list`]: `old_expression`
1181
1182Lambda forms (lambda expressions) have the same syntactic position as
1183expressions. They are a shorthand to create anonymous functions; the expression
1184``lambda arguments: expression`` yields a function object. The unnamed object
1185behaves like a function object defined with ::
1186
1187 def name(arguments):
1188 return expression
1189
1190See section :ref:`function` for the syntax of parameter lists. Note that
1191functions created with lambda forms cannot contain statements.
1192
1193.. _lambda:
1194
1195
1196.. _exprlists:
1197
1198Expression lists
1199================
1200
1201.. index:: pair: expression; list
1202
1203.. productionlist::
1204 expression_list: `expression` ( "," `expression` )* [","]
1205
1206.. index:: object: tuple
1207
1208An expression list containing at least one comma yields a tuple. The length of
1209the tuple is the number of expressions in the list. The expressions are
1210evaluated from left to right.
1211
1212.. index:: pair: trailing; comma
1213
1214The trailing comma is required only to create a single tuple (a.k.a. a
1215*singleton*); it is optional in all other cases. A single expression without a
1216trailing comma doesn't create a tuple, but rather yields the value of that
1217expression. (To create an empty tuple, use an empty pair of parentheses:
1218``()``.)
1219
1220
1221.. _evalorder:
1222
1223Evaluation order
1224================
1225
1226.. index:: pair: evaluation; order
1227
1228Python evaluates expressions from left to right. Notice that while evaluating an
1229assignment, the right-hand side is evaluated before the left-hand side.
1230
1231In the following lines, expressions will be evaluated in the arithmetic order of
1232their suffixes::
1233
1234 expr1, expr2, expr3, expr4
1235 (expr1, expr2, expr3, expr4)
1236 {expr1: expr2, expr3: expr4}
1237 expr1 + expr2 * (expr3 - expr4)
1238 func(expr1, expr2, *expr3, **expr4)
1239 expr3, expr4 = expr1, expr2
1240
1241
1242.. _operator-summary:
1243
1244Summary
1245=======
1246
1247.. index:: pair: operator; precedence
1248
1249The following table summarizes the operator precedences in Python, from lowest
1250precedence (least binding) to highest precedence (most binding). Operators in
1251the same box have the same precedence. Unless the syntax is explicitly given,
1252operators are binary. Operators in the same box group left to right (except for
1253comparisons, including tests, which all have the same precedence and chain from
1254left to right --- see section :ref:`comparisons` --- and exponentiation, which
1255groups from right to left).
1256
1257+-----------------------------------------------+-------------------------------------+
1258| Operator | Description |
1259+===============================================+=====================================+
1260| :keyword:`lambda` | Lambda expression |
1261+-----------------------------------------------+-------------------------------------+
1262| :keyword:`or` | Boolean OR |
1263+-----------------------------------------------+-------------------------------------+
1264| :keyword:`and` | Boolean AND |
1265+-----------------------------------------------+-------------------------------------+
1266| :keyword:`not` *x* | Boolean NOT |
1267+-----------------------------------------------+-------------------------------------+
1268| :keyword:`in`, :keyword:`not` :keyword:`in` | Membership tests |
1269+-----------------------------------------------+-------------------------------------+
1270| :keyword:`is`, :keyword:`is not` | Identity tests |
1271+-----------------------------------------------+-------------------------------------+
1272| ``<``, ``<=``, ``>``, ``>=``, ``<>``, ``!=``, | Comparisons |
1273| ``==`` | |
1274+-----------------------------------------------+-------------------------------------+
1275| ``|`` | Bitwise OR |
1276+-----------------------------------------------+-------------------------------------+
1277| ``^`` | Bitwise XOR |
1278+-----------------------------------------------+-------------------------------------+
1279| ``&`` | Bitwise AND |
1280+-----------------------------------------------+-------------------------------------+
1281| ``<<``, ``>>`` | Shifts |
1282+-----------------------------------------------+-------------------------------------+
1283| ``+``, ``-`` | Addition and subtraction |
1284+-----------------------------------------------+-------------------------------------+
1285| ``*``, ``/``, ``%`` | Multiplication, division, remainder |
1286+-----------------------------------------------+-------------------------------------+
1287| ``+x``, ``-x`` | Positive, negative |
1288+-----------------------------------------------+-------------------------------------+
1289| ``~x`` | Bitwise not |
1290+-----------------------------------------------+-------------------------------------+
1291| ``**`` | Exponentiation |
1292+-----------------------------------------------+-------------------------------------+
1293| ``x.attribute`` | Attribute reference |
1294+-----------------------------------------------+-------------------------------------+
1295| ``x[index]`` | Subscription |
1296+-----------------------------------------------+-------------------------------------+
1297| ``x[index:index]`` | Slicing |
1298+-----------------------------------------------+-------------------------------------+
1299| ``f(arguments...)`` | Function call |
1300+-----------------------------------------------+-------------------------------------+
1301| ``(expressions...)`` | Binding or tuple display |
1302+-----------------------------------------------+-------------------------------------+
1303| ``[expressions...]`` | List display |
1304+-----------------------------------------------+-------------------------------------+
1305| ``{key:datum...}`` | Dictionary display |
1306+-----------------------------------------------+-------------------------------------+
1307| ```expressions...``` | String conversion |
1308+-----------------------------------------------+-------------------------------------+
1309
1310.. rubric:: Footnotes
1311
1312.. [#] In Python 2.3, a list comprehension "leaks" the control variables of each
1313 ``for`` it contains into the containing scope. However, this behavior is
1314 deprecated, and relying on it will not work once this bug is fixed in a future
1315 release
1316
1317.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1318 true numerically due to roundoff. For example, and assuming a platform on which
1319 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1320 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1321 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod`
1322 in the :mod:`math` module returns a result whose sign matches the sign of the
1323 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1324 is more appropriate depends on the application.
1325
1326.. [#] If x is very close to an exact integer multiple of y, it's possible for
1327 ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding. In such
1328 cases, Python returns the latter result, in order to preserve that
1329 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1330
Mark Summerfield216ad332007-08-16 10:09:22 +00001331.. [#] While comparisons between unicode strings make sense at the byte
1332 level, they may be counter-intuitive to users. For example, the
1333 strings ``u"\u00C7"`` and ``u"\u0327\u0043"`` compare differently,
1334 even though they both represent the same unicode character (LATIN
1335 CAPTITAL LETTER C WITH CEDILLA).
1336
Georg Brandl8ec7f652007-08-15 14:28:01 +00001337.. [#] The implementation computes this efficiently, without constructing lists or
1338 sorting.
1339
1340.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
1341 value) lists, but this was very expensive for the common case of comparing for
1342 equality. An even earlier version of Python compared dictionaries by identity
1343 only, but this caused surprises because people expected to be able to test a
1344 dictionary for emptiness by comparing it to ``{}``.
1345