openfile(): Go back to opening the files in text mode. This undoes
[python/dscho.git] / Doc / ref / ref5.tex
blobef6cba904711223977aa9cde0022df3356f4e690
1 \chapter{Expressions\label{expressions}}
2 \index{expression}
4 This chapter explains the meaning of the elements of expressions in
5 Python.
7 \strong{Syntax Notes:} In this and the following chapters, extended
8 BNF\index{BNF} notation will be used to describe syntax, not lexical
9 analysis. When (one alternative of) a syntax rule has the form
11 \begin{productionlist}[*]
12 \production{name}{\token{othername}}
13 \end{productionlist}
15 and no semantics are given, the semantics of this form of \code{name}
16 are the same as for \code{othername}.
17 \index{syntax}
20 \section{Arithmetic conversions\label{conversions}}
21 \indexii{arithmetic}{conversion}
23 When a description of an arithmetic operator below uses the phrase
24 ``the numeric arguments are converted to a common type,'' the
25 arguments are coerced using the coercion rules listed at the end of
26 chapter \ref{datamodel}. If both arguments are standard numeric
27 types, the following coercions are applied:
29 \begin{itemize}
30 \item If either argument is a complex number, the other is converted
31 to complex;
32 \item otherwise, if either argument is a floating point number,
33 the other is converted to floating point;
34 \item otherwise, if either argument is a long integer,
35 the other is converted to long integer;
36 \item otherwise, both must be plain integers and no conversion
37 is necessary.
38 \end{itemize}
40 Some additional rules apply for certain operators (e.g., a string left
41 argument to the `\%' operator). Extensions can define their own
42 coercions.
45 \section{Atoms\label{atoms}}
46 \index{atom}
48 Atoms are the most basic elements of expressions. The simplest atoms
49 are identifiers or literals. Forms enclosed in
50 reverse quotes or in parentheses, brackets or braces are also
51 categorized syntactically as atoms. The syntax for atoms is:
53 \begin{productionlist}
54 \production{atom}
55 {\token{identifier} | \token{literal} | \token{enclosure}}
56 \production{enclosure}
57 {\token{parenth_form} | \token{list_display}}
58 \productioncont{| \token{dict_display} | \token{string_conversion}}
59 \end{productionlist}
62 \subsection{Identifiers (Names)\label{atom-identifiers}}
63 \index{name}
64 \index{identifier}
66 An identifier occurring as an atom is a name. See Section 4.1 for
67 documentation of naming and binding.
69 When the name is bound to an object, evaluation of the atom yields
70 that object. When a name is not bound, an attempt to evaluate it
71 raises a \exception{NameError} exception.
72 \exindex{NameError}
74 \strong{Private name mangling:}%
75 \indexii{name}{mangling}%
76 \indexii{private}{names}%
77 when an identifier that textually occurs in a class definition begins
78 with two or more underscore characters and does not end in two or more
79 underscores, it is considered a \dfn{private name} of that class.
80 Private names are transformed to a longer form before code is
81 generated for them. The transformation inserts the class name in
82 front of the name, with leading underscores removed, and a single
83 underscore inserted in front of the class name. For example, the
84 identifier \code{__spam} occurring in a class named \code{Ham} will be
85 transformed to \code{_Ham__spam}. This transformation is independent
86 of the syntactical context in which the identifier is used. If the
87 transformed name is extremely long (longer than 255 characters),
88 implementation defined truncation may happen. If the class name
89 consists only of underscores, no transformation is done.
92 \subsection{Literals\label{atom-literals}}
93 \index{literal}
95 Python supports string literals and various numeric literals:
97 \begin{productionlist}
98 \production{literal}
99 {\token{stringliteral} | \token{integer} | \token{longinteger}}
100 \productioncont{| \token{floatnumber} | \token{imagnumber}}
101 \end{productionlist}
103 Evaluation of a literal yields an object of the given type (string,
104 integer, long integer, floating point number, complex number) with the
105 given value. The value may be approximated in the case of floating
106 point and imaginary (complex) literals. See section \ref{literals}
107 for details.
109 All literals correspond to immutable data types, and hence the
110 object's identity is less important than its value. Multiple
111 evaluations of literals with the same value (either the same
112 occurrence in the program text or a different occurrence) may obtain
113 the same object or a different object with the same value.
114 \indexiii{immutable}{data}{type}
115 \indexii{immutable}{object}
118 \subsection{Parenthesized forms\label{parenthesized}}
119 \index{parenthesized form}
121 A parenthesized form is an optional expression list enclosed in
122 parentheses:
124 \begin{productionlist}
125 \production{parenth_form}
126 {"(" [\token{expression_list}] ")"}
127 \end{productionlist}
129 A parenthesized expression list yields whatever that expression list
130 yields: if the list contains at least one comma, it yields a tuple;
131 otherwise, it yields the single expression that makes up the
132 expression list.
134 An empty pair of parentheses yields an empty tuple object. Since
135 tuples are immutable, the rules for literals apply (i.e., two
136 occurrences of the empty tuple may or may not yield the same object).
137 \indexii{empty}{tuple}
139 Note that tuples are not formed by the parentheses, but rather by use
140 of the comma operator. The exception is the empty tuple, for which
141 parentheses \emph{are} required --- allowing unparenthesized ``nothing''
142 in expressions would cause ambiguities and allow common typos to
143 pass uncaught.
144 \index{comma}
145 \indexii{tuple}{display}
148 \subsection{List displays\label{lists}}
149 \indexii{list}{display}
150 \indexii{list}{comprehensions}
152 A list display is a possibly empty series of expressions enclosed in
153 square brackets:
155 \begin{productionlist}
156 \production{list_display}
157 {"[" [\token{listmaker}] "]"}
158 \production{listmaker}
159 {\token{expression} ( \token{list_for}
160 | ( "," \token{expression})* [","] )}
161 \production{list_iter}
162 {\token{list_for} | \token{list_if}}
163 \production{list_for}
164 {"for" \token{expression_list} "in" \token{testlist}
165 [\token{list_iter}]}
166 \production{list_if}
167 {"if" \token{test} [\token{list_iter}]}
168 \end{productionlist}
170 A list display yields a new list object. Its contents are specified
171 by providing either a list of expressions or a list comprehension.
172 \indexii{list}{comprehensions}
173 When a comma-separated list of expressions is supplied, its elements are
174 evaluated from left to right and placed into the list object in that
175 order. When a list comprehension is supplied, it consists of a
176 single expression followed by at least one \keyword{for} clause and zero or
177 more \keyword{for} or \keyword{if} clauses. In this
178 case, the elements of the new list are those that would be produced
179 by considering each of the \keyword{for} or \keyword{if} clauses a block,
180 nesting from
181 left to right, and evaluating the expression to produce a list element
182 each time the innermost block is reached.
183 \obindex{list}
184 \indexii{empty}{list}
187 \subsection{Dictionary displays\label{dict}}
188 \indexii{dictionary}{display}
190 A dictionary display is a possibly empty series of key/datum pairs
191 enclosed in curly braces:
192 \index{key}
193 \index{datum}
194 \index{key/datum pair}
196 \begin{productionlist}
197 \production{dict_display}
198 {"\{" [\token{key_datum_list}] "\}"}
199 \production{key_datum_list}
200 {\token{key_datum} ("," \token{key_datum})* [","]}
201 \production{key_datum}
202 {\token{expression} ":" \token{expression}}
203 \end{productionlist}
205 A dictionary display yields a new dictionary object.
206 \obindex{dictionary}
208 The key/datum pairs are evaluated from left to right to define the
209 entries of the dictionary: each key object is used as a key into the
210 dictionary to store the corresponding datum.
212 Restrictions on the types of the key values are listed earlier in
213 section \ref{types}. (To summarize,the key type should be hashable,
214 which excludes all mutable objects.) Clashes between duplicate keys
215 are not detected; the last datum (textually rightmost in the display)
216 stored for a given key value prevails.
217 \indexii{immutable}{object}
220 \subsection{String conversions\label{string-conversions}}
221 \indexii{string}{conversion}
222 \indexii{reverse}{quotes}
223 \indexii{backward}{quotes}
224 \index{back-quotes}
226 A string conversion is an expression list enclosed in reverse (a.k.a.
227 backward) quotes:
229 \begin{productionlist}
230 \production{string_conversion}
231 {"`" \token{expression_list} "`"}
232 \end{productionlist}
234 A string conversion evaluates the contained expression list and
235 converts the resulting object into a string according to rules
236 specific to its type.
238 If the object is a string, a number, \code{None}, or a tuple, list or
239 dictionary containing only objects whose type is one of these, the
240 resulting string is a valid Python expression which can be passed to
241 the built-in function \function{eval()} to yield an expression with the
242 same value (or an approximation, if floating point numbers are
243 involved).
245 (In particular, converting a string adds quotes around it and converts
246 ``funny'' characters to escape sequences that are safe to print.)
248 It is illegal to attempt to convert recursive objects (e.g., lists or
249 dictionaries that contain a reference to themselves, directly or
250 indirectly.)
251 \obindex{recursive}
253 The built-in function \function{repr()} performs exactly the same
254 conversion in its argument as enclosing it in parentheses and reverse
255 quotes does. The built-in function \function{str()} performs a
256 similar but more user-friendly conversion.
257 \bifuncindex{repr}
258 \bifuncindex{str}
261 \section{Primaries\label{primaries}}
262 \index{primary}
264 Primaries represent the most tightly bound operations of the language.
265 Their syntax is:
267 \begin{productionlist}
268 \production{primary}
269 {\token{atom} | \token{attributeref}
270 | \token{subscription} | \token{slicing} | \token{call}}
271 \end{productionlist}
274 \subsection{Attribute references\label{attribute-references}}
275 \indexii{attribute}{reference}
277 An attribute reference is a primary followed by a period and a name:
279 \begin{productionlist}
280 \production{attributeref}
281 {\token{primary} "." \token{identifier}}
282 \end{productionlist}
284 The primary must evaluate to an object of a type that supports
285 attribute references, e.g., a module, list, or an instance. This
286 object is then asked to produce the attribute whose name is the
287 identifier. If this attribute is not available, the exception
288 \exception{AttributeError}\exindex{AttributeError} is raised.
289 Otherwise, the type and value of the object produced is determined by
290 the object. Multiple evaluations of the same attribute reference may
291 yield different objects.
292 \obindex{module}
293 \obindex{list}
296 \subsection{Subscriptions\label{subscriptions}}
297 \index{subscription}
299 A subscription selects an item of a sequence (string, tuple or list)
300 or mapping (dictionary) object:
301 \obindex{sequence}
302 \obindex{mapping}
303 \obindex{string}
304 \obindex{tuple}
305 \obindex{list}
306 \obindex{dictionary}
307 \indexii{sequence}{item}
309 \begin{productionlist}
310 \production{subscription}
311 {\token{primary} "[" \token{expression_list} "]"}
312 \end{productionlist}
314 The primary must evaluate to an object of a sequence or mapping type.
316 If the primary is a mapping, the expression list must evaluate to an
317 object whose value is one of the keys of the mapping, and the
318 subscription selects the value in the mapping that corresponds to that
319 key. (The expression list is a tuple except if it has exactly one
320 item.)
322 If the primary is a sequence, the expression (list) must evaluate to a
323 plain integer. If this value is negative, the length of the sequence
324 is added to it (so that, e.g., \code{x[-1]} selects the last item of
325 \code{x}.) The resulting value must be a nonnegative integer less
326 than the number of items in the sequence, and the subscription selects
327 the item whose index is that value (counting from zero).
329 A string's items are characters. A character is not a separate data
330 type but a string of exactly one character.
331 \index{character}
332 \indexii{string}{item}
335 \subsection{Slicings\label{slicings}}
336 \index{slicing}
337 \index{slice}
339 A slicing selects a range of items in a sequence object (e.g., a
340 string, tuple or list). Slicings may be used as expressions or as
341 targets in assignment or del statements. The syntax for a slicing:
342 \obindex{sequence}
343 \obindex{string}
344 \obindex{tuple}
345 \obindex{list}
347 \begin{productionlist}
348 \production{slicing}
349 {\token{simple_slicing} | \token{extended_slicing}}
350 \production{simple_slicing}
351 {\token{primary} "[" \token{short_slice} "]"}
352 \production{extended_slicing}
353 {\token{primary} "[" \token{slice_list} "]" }
354 \production{slice_list}
355 {\token{slice_item} ("," \token{slice_item})* [","]}
356 \production{slice_item}
357 {\token{expression} | \token{proper_slice} | \token{ellipsis}}
358 \production{proper_slice}
359 {\token{short_slice} | \token{long_slice}}
360 \production{short_slice}
361 {[\token{lower_bound}] ":" [\token{upper_bound}]}
362 \production{long_slice}
363 {\token{short_slice} ":" [\token{stride}]}
364 \production{lower_bound}
365 {\token{expression}}
366 \production{upper_bound}
367 {\token{expression}}
368 \production{stride}
369 {\token{expression}}
370 \production{ellipsis}
371 {"..."}
372 \end{productionlist}
374 There is ambiguity in the formal syntax here: anything that looks like
375 an expression list also looks like a slice list, so any subscription
376 can be interpreted as a slicing. Rather than further complicating the
377 syntax, this is disambiguated by defining that in this case the
378 interpretation as a subscription takes priority over the
379 interpretation as a slicing (this is the case if the slice list
380 contains no proper slice nor ellipses). Similarly, when the slice
381 list has exactly one short slice and no trailing comma, the
382 interpretation as a simple slicing takes priority over that as an
383 extended slicing.\indexii{extended}{slicing}
385 The semantics for a simple slicing are as follows. The primary must
386 evaluate to a sequence object. The lower and upper bound expressions,
387 if present, must evaluate to plain integers; defaults are zero and the
388 \code{sys.maxint}, respectively. If either bound is negative, the
389 sequence's length is added to it. The slicing now selects all items
390 with index \var{k} such that
391 \code{\var{i} <= \var{k} < \var{j}} where \var{i}
392 and \var{j} are the specified lower and upper bounds. This may be an
393 empty sequence. It is not an error if \var{i} or \var{j} lie outside the
394 range of valid indexes (such items don't exist so they aren't
395 selected).
397 The semantics for an extended slicing are as follows. The primary
398 must evaluate to a mapping object, and it is indexed with a key that
399 is constructed from the slice list, as follows. If the slice list
400 contains at least one comma, the key is a tuple containing the
401 conversion of the slice items; otherwise, the conversion of the lone
402 slice item is the key. The conversion of a slice item that is an
403 expression is that expression. The conversion of an ellipsis slice
404 item is the built-in \code{Ellipsis} object. The conversion of a
405 proper slice is a slice object (see section \ref{types}) whose
406 \member{start}, \member{stop} and \member{step} attributes are the
407 values of the expressions given as lower bound, upper bound and
408 stride, respectively, substituting \code{None} for missing
409 expressions.
410 \withsubitem{(slice object attribute)}{\ttindex{start}
411 \ttindex{stop}\ttindex{step}}
414 \subsection{Calls\label{calls}}
415 \index{call}
417 A call calls a callable object (e.g., a function) with a possibly empty
418 series of arguments:
419 \obindex{callable}
421 \begin{productionlist}
422 \production{call}
423 {\token{primary} "(" [\token{argument_list} [","]] ")"}
424 \production{argument_list}
425 {\token{positional_arguments} ["," \token{keyword_arguments}]}
426 \productioncont{ ["," "*" \token{expression}]}
427 \productioncont{ ["," "**" \token{expression}]}
428 \productioncont{| \token{keyword_arguments} ["," "*" \token{expression}]}
429 \productioncont{ ["," "**" \token{expression}]}
430 \productioncont{| "*" \token{expression} ["," "**" \token{expression}]}
431 \productioncont{| "**" \token{expression}}
432 \production{positional_arguments}
433 {\token{expression} ("," \token{expression})*}
434 \production{keyword_arguments}
435 {\token{keyword_item} ("," \token{keyword_item})*}
436 \production{keyword_item}
437 {\token{identifier} "=" \token{expression}}
438 \end{productionlist}
440 A trailing comma may be present after an argument list but does not
441 affect the semantics.
443 The primary must evaluate to a callable object (user-defined
444 functions, built-in functions, methods of built-in objects, class
445 objects, methods of class instances, and certain class instances
446 themselves are callable; extensions may define additional callable
447 object types). All argument expressions are evaluated before the call
448 is attempted. Please refer to section \ref{function} for the syntax
449 of formal parameter lists.
451 If keyword arguments are present, they are first converted to
452 positional arguments, as follows. First, a list of unfilled slots is
453 created for the formal parameters. If there are N positional
454 arguments, they are placed in the first N slots. Next, for each
455 keyword argument, the identifier is used to determine the
456 corresponding slot (if the identifier is the same as the first formal
457 parameter name, the first slot is used, and so on). If the slot is
458 already filled, a \exception{TypeError} exception is raised.
459 Otherwise, the value of the argument is placed in the slot, filling it
460 (even if the expression is \code{None}, it fills the slot). When all
461 arguments have been processed, the slots that are still unfilled are
462 filled with the corresponding default value from the function
463 definition. (Default values are calculated, once, when the function
464 is defined; thus, a mutable object such as a list or dictionary used
465 as default value will be shared by all calls that don't specify an
466 argument value for the corresponding slot; this should usually be
467 avoided.) If there are any unfilled slots for which no default value
468 is specified, a \exception{TypeError} exception is raised. Otherwise,
469 the list of filled slots is used as the argument list for the call.
471 If there are more positional arguments than there are formal parameter
472 slots, a \exception{TypeError} exception is raised, unless a formal
473 parameter using the syntax \samp{*identifier} is present; in this
474 case, that formal parameter receives a tuple containing the excess
475 positional arguments (or an empty tuple if there were no excess
476 positional arguments).
478 If any keyword argument does not correspond to a formal parameter
479 name, a \exception{TypeError} exception is raised, unless a formal
480 parameter using the syntax \samp{**identifier} is present; in this
481 case, that formal parameter receives a dictionary containing the
482 excess keyword arguments (using the keywords as keys and the argument
483 values as corresponding values), or a (new) empty dictionary if there
484 were no excess keyword arguments.
486 If the syntax \samp{*expression} appears in the function call,
487 \samp{expression} must evaluate to a sequence. Elements from this
488 sequence are treated as if they were additional positional arguments;
489 if there are postional arguments \var{x1},...,\var{xN} , and
490 \samp{expression} evaluates to a sequence \var{y1},...,\var{yM}, this
491 is equivalent to a call with M+N positional arguments
492 \var{x1},...,\var{xN},\var{y1},...,\var{yM}.
494 A consequence of this is that although the \samp{*expression} syntax
495 appears \emph{after} any keyword arguments, it is processed
496 \emph{before} the keyword arguments (and the
497 \samp{**expression} argument, if any -- see below). So:
499 \begin{verbatim}
500 >>> def f(a, b):
501 ... print a, b
503 >>> f(b=1, *(2,))
505 >>> f(a=1, *(2,))
506 Traceback (most recent call last):
507 File "<stdin>", line 1, in ?
508 TypeError: f() got multiple values for keyword argument 'a'
509 >>> f(1, *(2,))
511 \end{verbatim}
513 It is unusual for both keyword arguments and the
514 \samp{*expression} syntax to be used in the same call, so in practice
515 this confusion does not arise.
517 If the syntax \samp{**expression} appears in the function call,
518 \samp{expression} must evaluate to a (subclass of) dictionary, the
519 contents of which are treated as additional keyword arguments. In the
520 case of a keyword appearing in both \samp{expression} and as an
521 explicit keyword argument, a \exception{TypeError} exception is
522 raised.
524 Formal parameters using the syntax \samp{*identifier} or
525 \samp{**identifier} cannot be used as positional argument slots or
526 as keyword argument names. Formal parameters using the syntax
527 \samp{(sublist)} cannot be used as keyword argument names; the
528 outermost sublist corresponds to a single unnamed argument slot, and
529 the argument value is assigned to the sublist using the usual tuple
530 assignment rules after all other parameter processing is done.
532 A call always returns some value, possibly \code{None}, unless it
533 raises an exception. How this value is computed depends on the type
534 of the callable object.
536 If it is---
538 \begin{description}
540 \item[a user-defined function:] The code block for the function is
541 executed, passing it the argument list. The first thing the code
542 block will do is bind the formal parameters to the arguments; this is
543 described in section \ref{function}. When the code block executes a
544 \keyword{return} statement, this specifies the return value of the
545 function call.
546 \indexii{function}{call}
547 \indexiii{user-defined}{function}{call}
548 \obindex{user-defined function}
549 \obindex{function}
551 \item[a built-in function or method:] The result is up to the
552 interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
553 Library Reference} for the descriptions of built-in functions and
554 methods.
555 \indexii{function}{call}
556 \indexii{built-in function}{call}
557 \indexii{method}{call}
558 \indexii{built-in method}{call}
559 \obindex{built-in method}
560 \obindex{built-in function}
561 \obindex{method}
562 \obindex{function}
564 \item[a class object:] A new instance of that class is returned.
565 \obindex{class}
566 \indexii{class object}{call}
568 \item[a class instance method:] The corresponding user-defined
569 function is called, with an argument list that is one longer than the
570 argument list of the call: the instance becomes the first argument.
571 \obindex{class instance}
572 \obindex{instance}
573 \indexii{class instance}{call}
575 \item[a class instance:] The class must define a \method{__call__()}
576 method; the effect is then the same as if that method was called.
577 \indexii{instance}{call}
578 \withsubitem{(object method)}{\ttindex{__call__()}}
580 \end{description}
583 \section{The power operator\label{power}}
585 The power operator binds more tightly than unary operators on its
586 left; it binds less tightly than unary operators on its right. The
587 syntax is:
589 \begin{productionlist}
590 \production{power}
591 {\token{primary} ["**" \token{u_expr}]}
592 \end{productionlist}
594 Thus, in an unparenthesized sequence of power and unary operators, the
595 operators are evaluated from right to left (this does not constrain
596 the evaluation order for the operands).
598 The power operator has the same semantics as the built-in
599 \function{pow()} function, when called with two arguments: it yields
600 its left argument raised to the power of its right argument. The
601 numeric arguments are first converted to a common type. The result
602 type is that of the arguments after coercion; if the result is not
603 expressible in that type (as in raising an integer to a negative
604 power, or a negative floating point number to a broken power), a
605 \exception{TypeError} exception is raised.
608 \section{Unary arithmetic operations \label{unary}}
609 \indexiii{unary}{arithmetic}{operation}
610 \indexiii{unary}{bit-wise}{operation}
612 All unary arithmetic (and bit-wise) operations have the same priority:
614 \begin{productionlist}
615 \production{u_expr}
616 {\token{power} | "-" \token{u_expr}
617 | "+" \token{u_expr} | "{\~}" \token{u_expr}}
618 \end{productionlist}
620 The unary \code{-} (minus) operator yields the negation of its
621 numeric argument.
622 \index{negation}
623 \index{minus}
625 The unary \code{+} (plus) operator yields its numeric argument
626 unchanged.
627 \index{plus}
629 The unary \code{\~} (invert) operator yields the bit-wise inversion
630 of its plain or long integer argument. The bit-wise inversion of
631 \code{x} is defined as \code{-(x+1)}. It only applies to integral
632 numbers.
633 \index{inversion}
635 In all three cases, if the argument does not have the proper type,
636 a \exception{TypeError} exception is raised.
637 \exindex{TypeError}
640 \section{Binary arithmetic operations\label{binary}}
641 \indexiii{binary}{arithmetic}{operation}
643 The binary arithmetic operations have the conventional priority
644 levels. Note that some of these operations also apply to certain
645 non-numeric types. Apart from the power operator, there are only two
646 levels, one for multiplicative operators and one for additive
647 operators:
649 \begin{productionlist}
650 \production{m_expr}
651 {\token{u_expr} | \token{m_expr} "*" \token{u_expr}
652 | \token{m_expr} "//" \token{u_expr}
653 | \token{m_expr} "/" \token{u_expr}}
654 \productioncont{| \token{m_expr} "\%" \token{u_expr}}
655 \production{a_expr}
656 {\token{m_expr} | \token{a_expr} "+" \token{m_expr}
657 | \token{a_expr} "-" \token{m_expr}}
658 \end{productionlist}
660 The \code{*} (multiplication) operator yields the product of its
661 arguments. The arguments must either both be numbers, or one argument
662 must be an integer (plain or long) and the other must be a sequence.
663 In the former case, the numbers are converted to a common type and
664 then multiplied together. In the latter case, sequence repetition is
665 performed; a negative repetition factor yields an empty sequence.
666 \index{multiplication}
668 The \code{/} (division) and \code{//} (floor division) operators yield
669 the quotient of their arguments. The numeric arguments are first
670 converted to a common type. Plain or long integer division yields an
671 integer of the same type; the result is that of mathematical division
672 with the `floor' function applied to the result. Division by zero
673 raises the
674 \exception{ZeroDivisionError} exception.
675 \exindex{ZeroDivisionError}
676 \index{division}
678 The \code{\%} (modulo) operator yields the remainder from the
679 division of the first argument by the second. The numeric arguments
680 are first converted to a common type. A zero right argument raises
681 the \exception{ZeroDivisionError} exception. The arguments may be floating
682 point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
683 \code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
684 yields a result with the same sign as its second operand (or zero);
685 the absolute value of the result is strictly smaller than the second
686 operand.
687 \index{modulo}
689 The integer division and modulo operators are connected by the
690 following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
691 modulo are also connected with the built-in function \function{divmod()}:
692 \code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
693 floating point numbers; there similar identities hold
694 approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
695 \code{floor(x/y) - 1} (for floats),\footnote{
696 If x is very close to an exact integer multiple of y, it's
697 possible for \code{floor(x/y)} to be one larger than
698 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
699 the latter result, in order to preserve that \code{divmod(x,y)[0]
700 * y + x \%{} y} be very close to \code{x}.
703 Complex floor division operator, modulo operator, and
704 \function{divmod()}.
706 \deprecated{2.3}{Instead convert to float using \function{abs()}
707 if appropriate.}
709 The \code{+} (addition) operator yields the sum of its arguments.
710 The arguments must either both be numbers or both sequences of the
711 same type. In the former case, the numbers are converted to a common
712 type and then added together. In the latter case, the sequences are
713 concatenated.
714 \index{addition}
716 The \code{-} (subtraction) operator yields the difference of its
717 arguments. The numeric arguments are first converted to a common
718 type.
719 \index{subtraction}
722 \section{Shifting operations\label{shifting}}
723 \indexii{shifting}{operation}
725 The shifting operations have lower priority than the arithmetic
726 operations:
728 \begin{productionlist}
729 \production{shift_expr}
730 {\token{a_expr}
731 | \token{shift_expr} ( "<<" | ">>" ) \token{a_expr}}
732 \end{productionlist}
734 These operators accept plain or long integers as arguments. The
735 arguments are converted to a common type. They shift the first
736 argument to the left or right by the number of bits given by the
737 second argument.
739 A right shift by \var{n} bits is defined as division by
740 \code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
741 multiplication with \code{pow(2,\var{n})}; for plain integers there is
742 no overflow check so in that case the operation drops bits and flips
743 the sign if the result is not less than \code{pow(2,31)} in absolute
744 value. Negative shift counts raise a \exception{ValueError}
745 exception.
746 \exindex{ValueError}
749 \section{Binary bit-wise operations\label{bitwise}}
750 \indexiii{binary}{bit-wise}{operation}
752 Each of the three bitwise operations has a different priority level:
754 \begin{productionlist}
755 \production{and_expr}
756 {\token{shift_expr} | \token{and_expr} "\&" \token{shift_expr}}
757 \production{xor_expr}
758 {\token{and_expr} | \token{xor_expr} "\textasciicircum" \token{and_expr}}
759 \production{or_expr}
760 {\token{xor_expr} | \token{or_expr} "|" \token{xor_expr}}
761 \end{productionlist}
763 The \code{\&} operator yields the bitwise AND of its arguments, which
764 must be plain or long integers. The arguments are converted to a
765 common type.
766 \indexii{bit-wise}{and}
768 The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
769 arguments, which must be plain or long integers. The arguments are
770 converted to a common type.
771 \indexii{bit-wise}{xor}
772 \indexii{exclusive}{or}
774 The \code{|} operator yields the bitwise (inclusive) OR of its
775 arguments, which must be plain or long integers. The arguments are
776 converted to a common type.
777 \indexii{bit-wise}{or}
778 \indexii{inclusive}{or}
781 \section{Comparisons\label{comparisons}}
782 \index{comparison}
784 Unlike C, all comparison operations in Python have the same priority,
785 which is lower than that of any arithmetic, shifting or bitwise
786 operation. Also unlike C, expressions like \code{a < b < c} have the
787 interpretation that is conventional in mathematics:
788 \indexii{C}{language}
790 \begin{productionlist}
791 \production{comparison}
792 {\token{or_expr} ( \token{comp_operator} \token{or_expr} )*}
793 \production{comp_operator}
794 {"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="}
795 \productioncont{| "is" ["not"] | ["not"] "in"}
796 \end{productionlist}
798 Comparisons yield integer values: \code{1} for true, \code{0} for false.
800 Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
801 equivalent to \code{x < y and y <= z}, except that \code{y} is
802 evaluated only once (but in both cases \code{z} is not evaluated at all
803 when \code{x < y} is found to be false).
804 \indexii{chaining}{comparisons}
806 Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
807 expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
808 operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
809 to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
810 \var{y opy z}, except that each expression is evaluated at most once.
812 Note that \var{a opa b opb c} doesn't imply any kind of comparison
813 between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
814 perfectly legal (though perhaps not pretty).
816 The forms \code{<>} and \code{!=} are equivalent; for consistency with
817 C, \code{!=} is preferred; where \code{!=} is mentioned below
818 \code{<>} is also accepted. The \code{<>} spelling is considered
819 obsolescent.
821 The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
822 \code{!=} compare
823 the values of two objects. The objects need not have the same type.
824 If both are numbers, they are converted to a common type. Otherwise,
825 objects of different types \emph{always} compare unequal, and are
826 ordered consistently but arbitrarily.
828 (This unusual definition of comparison was used to simplify the
829 definition of operations like sorting and the \keyword{in} and
830 \keyword{not in} operators. In the future, the comparison rules for
831 objects of different types are likely to change.)
833 Comparison of objects of the same type depends on the type:
835 \begin{itemize}
837 \item
838 Numbers are compared arithmetically.
840 \item
841 Strings are compared lexicographically using the numeric equivalents
842 (the result of the built-in function \function{ord()}) of their
843 characters. Unicode and 8-bit strings are fully interoperable in this
844 behavior.
846 \item
847 Tuples and lists are compared lexicographically using comparison of
848 corresponding items.
850 \item
851 Mappings (dictionaries) compare equal if and only if their sorted
852 (key, value) lists compare equal.\footnote{The implementation computes
853 this efficiently, without constructing lists or sorting.}
854 Outcomes other than equality are resolved consistently, but are not
855 otherwise defined.\footnote{Earlier versions of Python used
856 lexicographic comparison of the sorted (key, value) lists, but this
857 was very expensive for the common case of comparing for equality. An
858 even earlier version of Python compared dictionaries by identity only,
859 but this caused surprises because people expected to be able to test
860 a dictionary for emptiness by comparing it to \code{\{\}}.}
862 \item
863 Most other types compare unequal unless they are the same object;
864 the choice whether one object is considered smaller or larger than
865 another one is made arbitrarily but consistently within one
866 execution of a program.
868 \end{itemize}
870 The operators \keyword{in} and \keyword{not in} test for set
871 membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
872 is a member of the set \var{s}, and false otherwise. \code{\var{x}
873 not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
874 The set membership test has traditionally been bound to sequences; an
875 object is a member of a set if the set is a sequence and contains an
876 element equal to that object. However, it is possible for an object
877 to support membership tests without being a sequence. In particular,
878 dictionaries support memership testing as a nicer way of spelling
879 \code{\var{key} in \var{dict}}; other mapping types may follow suit.
881 For the list and tuple types, \code{\var{x} in \var{y}} is true if and
882 only if there exists an index \var{i} such that
883 \code{\var{x} == \var{y}[\var{i}]} is true.
885 For the Unicode and string types, \code{\var{x} in \var{y}} is true if
886 and only if there exists an index \var{i} such that \code{\var{x} ==
887 \var{y}[\var{i}]} is true. If \code{\var{x}} is not a string or
888 Unicode object of length \code{1}, a \exception{TypeError} exception
889 is raised.
891 For user-defined classes which define the \method{__contains__()} method,
892 \code{\var{x} in \var{y}} is true if and only if
893 \code{\var{y}.__contains__(\var{x})} is true.
895 For user-defined classes which do not define \method{__contains__()} and
896 do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
897 and only if there is a non-negative integer index \var{i} such that
898 \code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
899 do not raise \exception{IndexError} exception. (If any other exception
900 is raised, it is as if \keyword{in} raised that exception).
902 The operator \keyword{not in} is defined to have the inverse true value
903 of \keyword{in}.
904 \opindex{in}
905 \opindex{not in}
906 \indexii{membership}{test}
907 \obindex{sequence}
909 The operators \keyword{is} and \keyword{is not} test for object identity:
910 \code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
911 are the same object. \code{\var{x} is not \var{y}} yields the inverse
912 truth value.
913 \opindex{is}
914 \opindex{is not}
915 \indexii{identity}{test}
918 \section{Boolean operations\label{Booleans}}
919 \indexii{Boolean}{operation}
921 Boolean operations have the lowest priority of all Python operations:
923 \begin{productionlist}
924 \production{expression}
925 {\token{or_test} | \token{lambda_form}}
926 \production{or_test}
927 {\token{and_test} | \token{or_test} "or" \token{and_test}}
928 \production{and_test}
929 {\token{not_test} | \token{and_test} "and" \token{not_test}}
930 \production{not_test}
931 {\token{comparison} | "not" \token{not_test}}
932 \production{lambda_form}
933 {"lambda" [\token{parameter_list}]: \token{expression}}
934 \end{productionlist}
936 In the context of Boolean operations, and also when expressions are
937 used by control flow statements, the following values are interpreted
938 as false: \code{None}, numeric zero of all types, empty sequences
939 (strings, tuples and lists), and empty mappings (dictionaries). All
940 other values are interpreted as true.
942 The operator \keyword{not} yields \code{1} if its argument is false,
943 \code{0} otherwise.
944 \opindex{not}
946 The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
947 \var{x} is false, its value is returned; otherwise, \var{y} is
948 evaluated and the resulting value is returned.
949 \opindex{and}
951 The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
952 \var{x} is true, its value is returned; otherwise, \var{y} is
953 evaluated and the resulting value is returned.
954 \opindex{or}
956 (Note that neither \keyword{and} nor \keyword{or} restrict the value
957 and type they return to \code{0} and \code{1}, but rather return the
958 last evaluated argument.
959 This is sometimes useful, e.g., if \code{s} is a string that should be
960 replaced by a default value if it is empty, the expression
961 \code{s or 'foo'} yields the desired value. Because \keyword{not} has to
962 invent a value anyway, it does not bother to return a value of the
963 same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
964 not \code{''}.)
966 \section{Lambdas\label{lambdas}}
967 \indexii{lambda}{expression}
968 \indexii{lambda}{form}
969 \indexii{anonmymous}{function}
971 Lambda forms (lambda expressions) have the same syntactic position as
972 expressions. They are a shorthand to create anonymous functions; the
973 expression \code{lambda \var{arguments}: \var{expression}}
974 yields a function object. The unnamed object behaves like a function
975 object defined with
977 \begin{verbatim}
978 def name(arguments):
979 return expression
980 \end{verbatim}
982 See section \ref{function} for the syntax of parameter lists. Note
983 that functions created with lambda forms cannot contain statements.
984 \label{lambda}
986 \section{Expression lists\label{exprlists}}
987 \indexii{expression}{list}
989 \begin{productionlist}
990 \production{expression_list}
991 {\token{expression} ( "," \token{expression} )* [","]}
992 \end{productionlist}
994 An expression list containing at least one comma yields a
995 tuple. The length of the tuple is the number of expressions in the
996 list. The expressions are evaluated from left to right.
997 \obindex{tuple}
999 The trailing comma is required only to create a single tuple (a.k.a. a
1000 \emph{singleton}); it is optional in all other cases. A single
1001 expression without a trailing comma doesn't create a
1002 tuple, but rather yields the value of that expression.
1003 (To create an empty tuple, use an empty pair of parentheses:
1004 \code{()}.)
1005 \indexii{trailing}{comma}
1008 \section{Summary\label{summary}}
1010 The following table summarizes the operator
1011 precedences\indexii{operator}{precedence} in Python, from lowest
1012 precedence (least binding) to highest precedence (most binding).
1013 Operators in the same box have the same precedence. Unless the syntax
1014 is explicitly given, operators are binary. Operators in the same box
1015 group left to right (except for comparisons, which chain from left to
1016 right --- see above, and exponentiation, which groups from right to
1017 left).
1019 \begin{tableii}{c|l}{textrm}{Operator}{Description}
1020 \lineii{\keyword{lambda}} {Lambda expression}
1021 \hline
1022 \lineii{\keyword{or}} {Boolean OR}
1023 \hline
1024 \lineii{\keyword{and}} {Boolean AND}
1025 \hline
1026 \lineii{\keyword{not} \var{x}} {Boolean NOT}
1027 \hline
1028 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
1029 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
1030 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
1031 \code{<>}, \code{!=}, \code{==}}
1032 {Comparisons}
1033 \hline
1034 \lineii{\code{|}} {Bitwise OR}
1035 \hline
1036 \lineii{\code{\^}} {Bitwise XOR}
1037 \hline
1038 \lineii{\code{\&}} {Bitwise AND}
1039 \hline
1040 \lineii{\code{<}\code{<}, \code{>}\code{>}} {Shifts}
1041 \hline
1042 \lineii{\code{+}, \code{-}}{Addition and subtraction}
1043 \hline
1044 \lineii{\code{*}, \code{/}, \code{\%}}
1045 {Multiplication, division, remainder}
1046 \hline
1047 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
1048 \lineii{\code{\~\var{x}}} {Bitwise not}
1049 \hline
1050 \lineii{\code{**}} {Exponentiation}
1051 \hline
1052 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
1053 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
1054 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
1055 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
1056 \hline
1057 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
1058 \lineii{\code{[\var{expressions}\ldots]}} {List display}
1059 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
1060 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
1061 \end{tableii}