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