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