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