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