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