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 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 131 | .. index:: |
| 132 | single: parenthesized form |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 133 | single: () (parentheses); tuple display |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 134 | |
| 135 | A parenthesized form is an optional expression list enclosed in parentheses: |
| 136 | |
| 137 | .. productionlist:: |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 138 | parenth_form: "(" [`starred_expression`] ")" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 139 | |
| 140 | A parenthesized expression list yields whatever that expression list yields: if |
| 141 | the list contains at least one comma, it yields a tuple; otherwise, it yields |
| 142 | the single expression that makes up the expression list. |
| 143 | |
| 144 | .. index:: pair: empty; tuple |
| 145 | |
| 146 | An empty pair of parentheses yields an empty tuple object. Since tuples are |
| 147 | immutable, the rules for literals apply (i.e., two occurrences of the empty |
| 148 | tuple may or may not yield the same object). |
| 149 | |
| 150 | .. index:: |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 151 | single: comma; tuple display |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 152 | pair: tuple; display |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 153 | single: , (comma); tuple display |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 154 | |
| 155 | Note that tuples are not formed by the parentheses, but rather by use of the |
| 156 | comma operator. The exception is the empty tuple, for which parentheses *are* |
| 157 | required --- allowing unparenthesized "nothing" in expressions would cause |
| 158 | ambiguities and allow common typos to pass uncaught. |
| 159 | |
| 160 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 161 | .. _comprehensions: |
| 162 | |
| 163 | Displays for lists, sets and dictionaries |
| 164 | ----------------------------------------- |
| 165 | |
| 166 | For constructing a list, a set or a dictionary Python provides special syntax |
| 167 | called "displays", each of them in two flavors: |
| 168 | |
| 169 | * either the container contents are listed explicitly, or |
| 170 | |
| 171 | * they are computed via a set of looping and filtering instructions, called a |
| 172 | :dfn:`comprehension`. |
| 173 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 174 | .. index:: |
| 175 | single: for; in comprehensions |
| 176 | single: if; in comprehensions |
| 177 | single: async for; in comprehensions |
| 178 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 179 | Common syntax elements for comprehensions are: |
| 180 | |
| 181 | .. productionlist:: |
| 182 | comprehension: `expression` `comp_for` |
Serhiy Storchaka | d08972f | 2018-04-11 19:15:51 +0300 | [diff] [blame] | 183 | comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`] |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 184 | comp_iter: `comp_for` | `comp_if` |
| 185 | comp_if: "if" `expression_nocond` [`comp_iter`] |
| 186 | |
| 187 | The comprehension consists of a single expression followed by at least one |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 188 | :keyword:`!for` clause and zero or more :keyword:`!for` or :keyword:`!if` clauses. |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 189 | In this case, the elements of the new container are those that would be produced |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 190 | by considering each of the :keyword:`!for` or :keyword:`!if` clauses a block, |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 191 | nesting from left to right, and evaluating the expression to produce an element |
| 192 | each time the innermost block is reached. |
| 193 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 194 | However, aside from the iterable expression in the leftmost :keyword:`!for` clause, |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 195 | the comprehension is executed in a separate implicitly nested scope. This ensures |
| 196 | that names assigned to in the target list don't "leak" into the enclosing scope. |
| 197 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 198 | The iterable expression in the leftmost :keyword:`!for` clause is evaluated |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 199 | directly in the enclosing scope and then passed as an argument to the implictly |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 200 | nested scope. Subsequent :keyword:`!for` clauses and any filter condition in the |
| 201 | leftmost :keyword:`!for` clause cannot be evaluated in the enclosing scope as |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 202 | they may depend on the values obtained from the leftmost iterable. For example: |
| 203 | ``[x*y for x in range(10) for y in range(x, x+10)]``. |
| 204 | |
| 205 | To ensure the comprehension always results in a container of the appropriate |
| 206 | type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly |
Serhiy Storchaka | 07ca9af | 2018-02-04 10:53:48 +0200 | [diff] [blame] | 207 | nested scope. |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 208 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 209 | .. index:: |
| 210 | single: await; in comprehensions |
| 211 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 212 | Since Python 3.6, in an :keyword:`async def` function, an :keyword:`!async for` |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 213 | clause may be used to iterate over a :term:`asynchronous iterator`. |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 214 | A comprehension in an :keyword:`!async def` function may consist of either a |
| 215 | :keyword:`!for` or :keyword:`!async for` clause following the leading |
| 216 | expression, may contain additional :keyword:`!for` or :keyword:`!async for` |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 217 | clauses, and may also use :keyword:`await` expressions. |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 218 | If a comprehension contains either :keyword:`!async for` clauses |
| 219 | or :keyword:`!await` expressions it is called an |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 220 | :dfn:`asynchronous comprehension`. An asynchronous comprehension may |
| 221 | suspend the execution of the coroutine function in which it appears. |
| 222 | See also :pep:`530`. |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 223 | |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 224 | .. versionadded:: 3.6 |
| 225 | Asynchronous comprehensions were introduced. |
| 226 | |
Serhiy Storchaka | 07ca9af | 2018-02-04 10:53:48 +0200 | [diff] [blame] | 227 | .. versionchanged:: 3.8 |
| 228 | ``yield`` and ``yield from`` prohibited in the implicitly nested scope. |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 229 | |
| 230 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 231 | .. _lists: |
| 232 | |
| 233 | List displays |
| 234 | ------------- |
| 235 | |
| 236 | .. index:: |
| 237 | pair: list; display |
| 238 | pair: list; comprehensions |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 239 | pair: empty; list |
| 240 | object: list |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 241 | single: [] (square brackets); list expression |
| 242 | single: , (comma); expression list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 243 | |
| 244 | A list display is a possibly empty series of expressions enclosed in square |
| 245 | brackets: |
| 246 | |
| 247 | .. productionlist:: |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 248 | list_display: "[" [`starred_list` | `comprehension`] "]" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 249 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 250 | A list display yields a new list object, the contents being specified by either |
| 251 | a list of expressions or a comprehension. When a comma-separated list of |
| 252 | expressions is supplied, its elements are evaluated from left to right and |
| 253 | placed into the list object in that order. When a comprehension is supplied, |
| 254 | the list is constructed from the elements resulting from the comprehension. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 255 | |
| 256 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 257 | .. _set: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 258 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 259 | Set displays |
| 260 | ------------ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 261 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 262 | .. index:: |
| 263 | pair: set; display |
| 264 | object: set |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 265 | single: {} (curly brackets); set expression |
| 266 | single: , (comma); expression list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 267 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 268 | A set display is denoted by curly braces and distinguishable from dictionary |
| 269 | displays by the lack of colons separating keys and values: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 270 | |
| 271 | .. productionlist:: |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 272 | set_display: "{" (`starred_list` | `comprehension`) "}" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 273 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 274 | A set display yields a new mutable set object, the contents being specified by |
| 275 | either a sequence of expressions or a comprehension. When a comma-separated |
| 276 | list of expressions is supplied, its elements are evaluated from left to right |
| 277 | and added to the set object. When a comprehension is supplied, the set is |
| 278 | constructed from the elements resulting from the comprehension. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 279 | |
Georg Brandl | 528cdb1 | 2008-09-21 07:09:51 +0000 | [diff] [blame] | 280 | An empty set cannot be constructed with ``{}``; this literal constructs an empty |
| 281 | dictionary. |
Christian Heimes | 7864476 | 2008-03-04 23:39:23 +0000 | [diff] [blame] | 282 | |
| 283 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 284 | .. _dict: |
| 285 | |
| 286 | Dictionary displays |
| 287 | ------------------- |
| 288 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 289 | .. index:: |
| 290 | pair: dictionary; display |
| 291 | key, datum, key/datum pair |
| 292 | object: dictionary |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 293 | single: {} (curly brackets); dictionary expression |
| 294 | single: : (colon); in dictionary expressions |
| 295 | single: , (comma); in dictionary displays |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 296 | |
| 297 | A dictionary display is a possibly empty series of key/datum pairs enclosed in |
| 298 | curly braces: |
| 299 | |
| 300 | .. productionlist:: |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 301 | dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 302 | key_datum_list: `key_datum` ("," `key_datum`)* [","] |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 303 | key_datum: `expression` ":" `expression` | "**" `or_expr` |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 304 | dict_comprehension: `expression` ":" `expression` `comp_for` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 305 | |
| 306 | A dictionary display yields a new dictionary object. |
| 307 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 308 | If a comma-separated sequence of key/datum pairs is given, they are evaluated |
| 309 | from left to right to define the entries of the dictionary: each key object is |
| 310 | used as a key into the dictionary to store the corresponding datum. This means |
| 311 | that you can specify the same key multiple times in the key/datum list, and the |
| 312 | final dictionary's value for that key will be the last one given. |
| 313 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 314 | .. index:: |
| 315 | unpacking; dictionary |
| 316 | single: **; in dictionary displays |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 317 | |
| 318 | A double asterisk ``**`` denotes :dfn:`dictionary unpacking`. |
| 319 | Its operand must be a :term:`mapping`. Each mapping item is added |
| 320 | to the new dictionary. Later values replace values already set by |
| 321 | earlier key/datum pairs and earlier dictionary unpackings. |
| 322 | |
| 323 | .. versionadded:: 3.5 |
| 324 | Unpacking into dictionary displays, originally proposed by :pep:`448`. |
| 325 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 326 | A dict comprehension, in contrast to list and set comprehensions, needs two |
| 327 | expressions separated with a colon followed by the usual "for" and "if" clauses. |
| 328 | When the comprehension is run, the resulting key and value elements are inserted |
| 329 | in the new dictionary in the order they are produced. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 330 | |
| 331 | .. index:: pair: immutable; object |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 332 | hashable |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 333 | |
| 334 | 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] | 335 | :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] | 336 | all mutable objects.) Clashes between duplicate keys are not detected; the last |
| 337 | datum (textually rightmost in the display) stored for a given key value |
| 338 | prevails. |
| 339 | |
| 340 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 341 | .. _genexpr: |
| 342 | |
| 343 | Generator expressions |
| 344 | --------------------- |
| 345 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 346 | .. index:: |
| 347 | pair: generator; expression |
| 348 | object: generator |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 349 | single: () (parentheses); generator expression |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 350 | |
| 351 | A generator expression is a compact generator notation in parentheses: |
| 352 | |
| 353 | .. productionlist:: |
| 354 | generator_expression: "(" `expression` `comp_for` ")" |
| 355 | |
| 356 | A generator expression yields a new generator object. Its syntax is the same as |
| 357 | for comprehensions, except that it is enclosed in parentheses instead of |
| 358 | brackets or curly braces. |
| 359 | |
| 360 | Variables used in the generator expression are evaluated lazily when the |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 361 | :meth:`~generator.__next__` method is called for the generator object (in the same |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 362 | fashion as normal generators). However, the iterable expression in the |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 363 | leftmost :keyword:`!for` clause is immediately evaluated, so that an error |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 364 | produced by it will be emitted at the point where the generator expression |
| 365 | is defined, rather than at the point where the first value is retrieved. |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 366 | Subsequent :keyword:`!for` clauses and any filter condition in the leftmost |
| 367 | :keyword:`!for` clause cannot be evaluated in the enclosing scope as they may |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 368 | depend on the values obtained from the leftmost iterable. For example: |
| 369 | ``(x*y for x in range(10) for y in range(x, x+10))``. |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 370 | |
| 371 | 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] | 372 | :ref:`calls` for details. |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 373 | |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 374 | To avoid interfering with the expected operation of the generator expression |
| 375 | itself, ``yield`` and ``yield from`` expressions are prohibited in the |
Serhiy Storchaka | 07ca9af | 2018-02-04 10:53:48 +0200 | [diff] [blame] | 376 | implicitly defined generator. |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 377 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 378 | If a generator expression contains either :keyword:`!async for` |
Yury Selivanov | b8ab9d3 | 2017-10-06 02:58:28 -0400 | [diff] [blame] | 379 | clauses or :keyword:`await` expressions it is called an |
| 380 | :dfn:`asynchronous generator expression`. An asynchronous generator |
| 381 | expression returns a new asynchronous generator object, |
| 382 | which is an asynchronous iterator (see :ref:`async-iterators`). |
| 383 | |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 384 | .. versionadded:: 3.6 |
| 385 | Asynchronous generator expressions were introduced. |
| 386 | |
Yury Selivanov | b8ab9d3 | 2017-10-06 02:58:28 -0400 | [diff] [blame] | 387 | .. versionchanged:: 3.7 |
| 388 | Prior to Python 3.7, asynchronous generator expressions could |
| 389 | only appear in :keyword:`async def` coroutines. Starting |
| 390 | with 3.7, any function can use asynchronous generator expressions. |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 391 | |
Serhiy Storchaka | 07ca9af | 2018-02-04 10:53:48 +0200 | [diff] [blame] | 392 | .. versionchanged:: 3.8 |
| 393 | ``yield`` and ``yield from`` prohibited in the implicitly nested scope. |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 394 | |
| 395 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 396 | .. _yieldexpr: |
| 397 | |
| 398 | Yield expressions |
| 399 | ----------------- |
| 400 | |
| 401 | .. index:: |
| 402 | keyword: yield |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 403 | keyword: from |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 404 | pair: yield; expression |
| 405 | pair: generator; function |
| 406 | |
| 407 | .. productionlist:: |
| 408 | yield_atom: "(" `yield_expression` ")" |
Nick Coghlan | 1f7ce62 | 2012-01-13 21:43:40 +1000 | [diff] [blame] | 409 | yield_expression: "yield" [`expression_list` | "from" `expression`] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 410 | |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 411 | The yield expression is used when defining a :term:`generator` function |
| 412 | or an :term:`asynchronous generator` function and |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 413 | thus can only be used in the body of a function definition. Using a yield |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 414 | expression in a function's body causes that function to be a generator, |
| 415 | and using it in an :keyword:`async def` function's body causes that |
| 416 | coroutine function to be an asynchronous generator. For example:: |
| 417 | |
| 418 | def gen(): # defines a generator function |
| 419 | yield 123 |
| 420 | |
Andrés Delfino | bfe1839 | 2018-11-07 15:12:12 -0300 | [diff] [blame] | 421 | async def agen(): # defines an asynchronous generator function |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 422 | yield 123 |
| 423 | |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 424 | Due to their side effects on the containing scope, ``yield`` expressions |
| 425 | are not permitted as part of the implicitly defined scopes used to |
Serhiy Storchaka | 07ca9af | 2018-02-04 10:53:48 +0200 | [diff] [blame] | 426 | implement comprehensions and generator expressions. |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 427 | |
Serhiy Storchaka | 07ca9af | 2018-02-04 10:53:48 +0200 | [diff] [blame] | 428 | .. versionchanged:: 3.8 |
| 429 | Yield expressions prohibited in the implicitly nested scopes used to |
Serhiy Storchaka | 73a7e9b | 2017-12-01 06:54:17 +0200 | [diff] [blame] | 430 | implement comprehensions and generator expressions. |
| 431 | |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 432 | Generator functions are described below, while asynchronous generator |
| 433 | functions are described separately in section |
| 434 | :ref:`asynchronous-generator-functions`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 435 | |
| 436 | When a generator function is called, it returns an iterator known as a |
Guido van Rossum | d0150ad | 2015-05-05 12:02:01 -0700 | [diff] [blame] | 437 | generator. That generator then controls the execution of the generator function. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 438 | 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] | 439 | time, the execution proceeds to the first yield expression, where it is |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 440 | 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] | 441 | caller. By suspended, we mean that all local state is retained, including the |
Ethan Furman | 2f825af | 2015-01-14 22:25:27 -0800 | [diff] [blame] | 442 | current bindings of local variables, the instruction pointer, the internal |
| 443 | evaluation stack, and the state of any exception handling. When the execution |
| 444 | is resumed by calling one of the |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 445 | 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] | 446 | were just another external call. The value of the yield expression after |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 447 | resuming depends on the method which resumed the execution. If |
| 448 | :meth:`~generator.__next__` is used (typically via either a :keyword:`for` or |
| 449 | the :func:`next` builtin) then the result is :const:`None`. Otherwise, if |
| 450 | :meth:`~generator.send` is used, then the result will be the value passed in to |
| 451 | that method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 452 | |
| 453 | .. index:: single: coroutine |
| 454 | |
| 455 | All of this makes generator functions quite similar to coroutines; they yield |
| 456 | multiple times, they have more than one entry point and their execution can be |
| 457 | suspended. The only difference is that a generator function cannot control |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 458 | where the execution should continue after it yields; the control is always |
Georg Brandl | 6faee4e | 2010-09-21 14:48:28 +0000 | [diff] [blame] | 459 | transferred to the generator's caller. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 460 | |
Ethan Furman | 2f825af | 2015-01-14 22:25:27 -0800 | [diff] [blame] | 461 | Yield expressions are allowed anywhere in a :keyword:`try` construct. If the |
| 462 | generator is not resumed before it is |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 463 | finalized (by reaching a zero reference count or by being garbage collected), |
| 464 | the generator-iterator's :meth:`~generator.close` method will be called, |
| 465 | allowing any pending :keyword:`finally` clauses to execute. |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 466 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 467 | .. index:: |
| 468 | single: from; yield from expression |
| 469 | |
Nick Coghlan | 0ed8019 | 2012-01-14 14:43:24 +1000 | [diff] [blame] | 470 | When ``yield from <expr>`` is used, it treats the supplied expression as |
Nick Coghlan | 1f7ce62 | 2012-01-13 21:43:40 +1000 | [diff] [blame] | 471 | a subiterator. All values produced by that subiterator are passed directly |
| 472 | 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] | 473 | :meth:`~generator.send` and any exceptions passed in with |
| 474 | :meth:`~generator.throw` are passed to the underlying iterator if it has the |
| 475 | appropriate methods. If this is not the case, then :meth:`~generator.send` |
| 476 | will raise :exc:`AttributeError` or :exc:`TypeError`, while |
| 477 | :meth:`~generator.throw` will just raise the passed in exception immediately. |
Nick Coghlan | 1f7ce62 | 2012-01-13 21:43:40 +1000 | [diff] [blame] | 478 | |
| 479 | When the underlying iterator is complete, the :attr:`~StopIteration.value` |
| 480 | attribute of the raised :exc:`StopIteration` instance becomes the value of |
| 481 | the yield expression. It can be either set explicitly when raising |
| 482 | :exc:`StopIteration`, or automatically when the sub-iterator is a generator |
| 483 | (by returning a value from the sub-generator). |
| 484 | |
Nick Coghlan | 0ed8019 | 2012-01-14 14:43:24 +1000 | [diff] [blame] | 485 | .. versionchanged:: 3.3 |
Martin Panter | d21e0b5 | 2015-10-10 10:36:22 +0000 | [diff] [blame] | 486 | Added ``yield from <expr>`` to delegate control flow to a subiterator. |
Nick Coghlan | 0ed8019 | 2012-01-14 14:43:24 +1000 | [diff] [blame] | 487 | |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 488 | The parentheses may be omitted when the yield expression is the sole expression |
| 489 | on the right hand side of an assignment statement. |
| 490 | |
| 491 | .. seealso:: |
| 492 | |
Serhiy Storchaka | e4ba872 | 2016-03-31 15:30:54 +0300 | [diff] [blame] | 493 | :pep:`255` - Simple Generators |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 494 | The proposal for adding generators and the :keyword:`yield` statement to Python. |
| 495 | |
Serhiy Storchaka | e4ba872 | 2016-03-31 15:30:54 +0300 | [diff] [blame] | 496 | :pep:`342` - Coroutines via Enhanced Generators |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 497 | The proposal to enhance the API and syntax of generators, making them |
| 498 | usable as simple coroutines. |
| 499 | |
Serhiy Storchaka | e4ba872 | 2016-03-31 15:30:54 +0300 | [diff] [blame] | 500 | :pep:`380` - Syntax for Delegating to a Subgenerator |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 501 | The proposal to introduce the :token:`yield_from` syntax, making delegation |
| 502 | to sub-generators easy. |
Nick Coghlan | 1f7ce62 | 2012-01-13 21:43:40 +1000 | [diff] [blame] | 503 | |
Andrés Delfino | bfe1839 | 2018-11-07 15:12:12 -0300 | [diff] [blame] | 504 | :pep:`525` - Asynchronous Generators |
| 505 | The proposal that expanded on :pep:`492` by adding generator capabilities to |
| 506 | coroutine functions. |
| 507 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 508 | .. index:: object: generator |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 509 | .. _generator-methods: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 510 | |
R David Murray | 2c1d1d6 | 2012-08-17 20:48:59 -0400 | [diff] [blame] | 511 | Generator-iterator methods |
| 512 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 513 | |
| 514 | This subsection describes the methods of a generator iterator. They can |
| 515 | be used to control the execution of a generator function. |
| 516 | |
| 517 | Note that calling any of the generator methods below when the generator |
| 518 | is already executing raises a :exc:`ValueError` exception. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 519 | |
| 520 | .. index:: exception: StopIteration |
| 521 | |
| 522 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 523 | .. method:: generator.__next__() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 524 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 525 | 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] | 526 | executed yield expression. When a generator function is resumed with a |
| 527 | :meth:`~generator.__next__` method, the current yield expression always |
| 528 | evaluates to :const:`None`. The execution then continues to the next yield |
| 529 | expression, where the generator is suspended again, and the value of the |
Serhiy Storchaka | 848c8b2 | 2014-09-05 23:27:36 +0300 | [diff] [blame] | 530 | :token:`expression_list` is returned to :meth:`__next__`'s caller. If the |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 531 | generator exits without yielding another value, a :exc:`StopIteration` |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 532 | exception is raised. |
| 533 | |
| 534 | This method is normally called implicitly, e.g. by a :keyword:`for` loop, or |
| 535 | by the built-in :func:`next` function. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 536 | |
| 537 | |
| 538 | .. method:: generator.send(value) |
| 539 | |
| 540 | Resumes the execution and "sends" a value into the generator function. The |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 541 | *value* argument becomes the result of the current yield expression. The |
| 542 | :meth:`send` method returns the next value yielded by the generator, or |
| 543 | raises :exc:`StopIteration` if the generator exits without yielding another |
| 544 | value. When :meth:`send` is called to start the generator, it must be called |
| 545 | with :const:`None` as the argument, because there is no yield expression that |
| 546 | could receive the value. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 547 | |
| 548 | |
| 549 | .. method:: generator.throw(type[, value[, traceback]]) |
| 550 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 551 | 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] | 552 | and returns the next value yielded by the generator function. If the generator |
| 553 | exits without yielding another value, a :exc:`StopIteration` exception is |
| 554 | raised. If the generator function does not catch the passed-in exception, or |
| 555 | raises a different exception, then that exception propagates to the caller. |
| 556 | |
| 557 | .. index:: exception: GeneratorExit |
| 558 | |
| 559 | |
| 560 | .. method:: generator.close() |
| 561 | |
| 562 | Raises a :exc:`GeneratorExit` at the point where the generator function was |
Yury Selivanov | 8170e8c | 2015-05-09 11:44:30 -0400 | [diff] [blame] | 563 | paused. If the generator function then exits gracefully, is already closed, |
| 564 | or raises :exc:`GeneratorExit` (by not catching the exception), close |
| 565 | returns to its caller. If the generator yields a value, a |
| 566 | :exc:`RuntimeError` is raised. If the generator raises any other exception, |
| 567 | it is propagated to the caller. :meth:`close` does nothing if the generator |
| 568 | has already exited due to an exception or normal exit. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 569 | |
Chris Jerdonek | 2654b86 | 2012-12-23 15:31:57 -0800 | [diff] [blame] | 570 | .. index:: single: yield; examples |
| 571 | |
| 572 | Examples |
| 573 | ^^^^^^^^ |
| 574 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 575 | Here is a simple example that demonstrates the behavior of generators and |
| 576 | generator functions:: |
| 577 | |
| 578 | >>> def echo(value=None): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 579 | ... print("Execution starts when 'next()' is called for the first time.") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 580 | ... try: |
| 581 | ... while True: |
| 582 | ... try: |
| 583 | ... value = (yield value) |
Georg Brandl | fe800a3 | 2009-08-03 17:50:20 +0000 | [diff] [blame] | 584 | ... except Exception as e: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 585 | ... value = e |
| 586 | ... finally: |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 587 | ... print("Don't forget to clean up when 'close()' is called.") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 588 | ... |
| 589 | >>> generator = echo(1) |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 590 | >>> print(next(generator)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 591 | Execution starts when 'next()' is called for the first time. |
| 592 | 1 |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 593 | >>> print(next(generator)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 594 | None |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 595 | >>> print(generator.send(2)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 596 | 2 |
| 597 | >>> generator.throw(TypeError, "spam") |
| 598 | TypeError('spam',) |
| 599 | >>> generator.close() |
| 600 | Don't forget to clean up when 'close()' is called. |
| 601 | |
Chris Jerdonek | 2654b86 | 2012-12-23 15:31:57 -0800 | [diff] [blame] | 602 | For examples using ``yield from``, see :ref:`pep-380` in "What's New in |
| 603 | Python." |
| 604 | |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 605 | .. _asynchronous-generator-functions: |
| 606 | |
| 607 | Asynchronous generator functions |
| 608 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 609 | |
| 610 | The presence of a yield expression in a function or method defined using |
| 611 | :keyword:`async def` further defines the function as a |
| 612 | :term:`asynchronous generator` function. |
| 613 | |
| 614 | When an asynchronous generator function is called, it returns an |
| 615 | asynchronous iterator known as an asynchronous generator object. |
| 616 | That object then controls the execution of the generator function. |
| 617 | An asynchronous generator object is typically used in an |
| 618 | :keyword:`async for` statement in a coroutine function analogously to |
| 619 | how a generator object would be used in a :keyword:`for` statement. |
| 620 | |
| 621 | Calling one of the asynchronous generator's methods returns an |
| 622 | :term:`awaitable` object, and the execution starts when this object |
| 623 | is awaited on. At that time, the execution proceeds to the first yield |
| 624 | expression, where it is suspended again, returning the value of |
| 625 | :token:`expression_list` to the awaiting coroutine. As with a generator, |
| 626 | suspension means that all local state is retained, including the |
| 627 | current bindings of local variables, the instruction pointer, the internal |
| 628 | evaluation stack, and the state of any exception handling. When the execution |
| 629 | is resumed by awaiting on the next object returned by the asynchronous |
| 630 | generator's methods, the function can proceed exactly as if the yield |
| 631 | expression were just another external call. The value of the yield expression |
| 632 | after resuming depends on the method which resumed the execution. If |
| 633 | :meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if |
| 634 | :meth:`~agen.asend` is used, then the result will be the value passed in to |
| 635 | that method. |
| 636 | |
| 637 | In an asynchronous generator function, yield expressions are allowed anywhere |
| 638 | in a :keyword:`try` construct. However, if an asynchronous generator is not |
| 639 | resumed before it is finalized (by reaching a zero reference count or by |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 640 | being garbage collected), then a yield expression within a :keyword:`!try` |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 641 | construct could result in a failure to execute pending :keyword:`finally` |
| 642 | clauses. In this case, it is the responsibility of the event loop or |
| 643 | scheduler running the asynchronous generator to call the asynchronous |
| 644 | generator-iterator's :meth:`~agen.aclose` method and run the resulting |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 645 | coroutine object, thus allowing any pending :keyword:`!finally` clauses |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 646 | to execute. |
| 647 | |
| 648 | To take care of finalization, an event loop should define |
| 649 | a *finalizer* function which takes an asynchronous generator-iterator |
| 650 | and presumably calls :meth:`~agen.aclose` and executes the coroutine. |
| 651 | This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`. |
| 652 | When first iterated over, an asynchronous generator-iterator will store the |
| 653 | registered *finalizer* to be called upon finalization. For a reference example |
| 654 | of a *finalizer* method see the implementation of |
| 655 | ``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`. |
| 656 | |
| 657 | The expression ``yield from <expr>`` is a syntax error when used in an |
| 658 | asynchronous generator function. |
| 659 | |
| 660 | .. index:: object: asynchronous-generator |
| 661 | .. _asynchronous-generator-methods: |
| 662 | |
| 663 | Asynchronous generator-iterator methods |
| 664 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 665 | |
| 666 | This subsection describes the methods of an asynchronous generator iterator, |
| 667 | which are used to control the execution of a generator function. |
| 668 | |
| 669 | |
| 670 | .. index:: exception: StopAsyncIteration |
| 671 | |
| 672 | .. coroutinemethod:: agen.__anext__() |
| 673 | |
| 674 | Returns an awaitable which when run starts to execute the asynchronous |
| 675 | generator or resumes it at the last executed yield expression. When an |
| 676 | asynchronous generator function is resumed with a :meth:`~agen.__anext__` |
| 677 | method, the current yield expression always evaluates to :const:`None` in |
| 678 | the returned awaitable, which when run will continue to the next yield |
| 679 | expression. The value of the :token:`expression_list` of the yield |
| 680 | expression is the value of the :exc:`StopIteration` exception raised by |
| 681 | the completing coroutine. If the asynchronous generator exits without |
| 682 | yielding another value, the awaitable instead raises an |
| 683 | :exc:`StopAsyncIteration` exception, signalling that the asynchronous |
| 684 | iteration has completed. |
| 685 | |
| 686 | This method is normally called implicitly by a :keyword:`async for` loop. |
| 687 | |
| 688 | |
| 689 | .. coroutinemethod:: agen.asend(value) |
| 690 | |
| 691 | Returns an awaitable which when run resumes the execution of the |
| 692 | asynchronous generator. As with the :meth:`~generator.send()` method for a |
| 693 | generator, this "sends" a value into the asynchronous generator function, |
| 694 | and the *value* argument becomes the result of the current yield expression. |
| 695 | The awaitable returned by the :meth:`asend` method will return the next |
| 696 | value yielded by the generator as the value of the raised |
| 697 | :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the |
| 698 | asynchronous generator exits without yielding another value. When |
| 699 | :meth:`asend` is called to start the asynchronous |
| 700 | generator, it must be called with :const:`None` as the argument, |
| 701 | because there is no yield expression that could receive the value. |
| 702 | |
| 703 | |
| 704 | .. coroutinemethod:: agen.athrow(type[, value[, traceback]]) |
| 705 | |
| 706 | Returns an awaitable that raises an exception of type ``type`` at the point |
| 707 | where the asynchronous generator was paused, and returns the next value |
| 708 | yielded by the generator function as the value of the raised |
| 709 | :exc:`StopIteration` exception. If the asynchronous generator exits |
| 710 | without yielding another value, an :exc:`StopAsyncIteration` exception is |
| 711 | raised by the awaitable. |
| 712 | If the generator function does not catch the passed-in exception, or |
delirious-lettuce | 3378b20 | 2017-05-19 14:37:57 -0600 | [diff] [blame] | 713 | raises a different exception, then when the awaitable is run that exception |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 714 | propagates to the caller of the awaitable. |
| 715 | |
| 716 | .. index:: exception: GeneratorExit |
| 717 | |
| 718 | |
| 719 | .. coroutinemethod:: agen.aclose() |
| 720 | |
| 721 | Returns an awaitable that when run will throw a :exc:`GeneratorExit` into |
| 722 | the asynchronous generator function at the point where it was paused. |
| 723 | If the asynchronous generator function then exits gracefully, is already |
| 724 | closed, or raises :exc:`GeneratorExit` (by not catching the exception), |
| 725 | then the returned awaitable will raise a :exc:`StopIteration` exception. |
| 726 | Any further awaitables returned by subsequent calls to the asynchronous |
| 727 | generator will raise a :exc:`StopAsyncIteration` exception. If the |
| 728 | asynchronous generator yields a value, a :exc:`RuntimeError` is raised |
| 729 | by the awaitable. If the asynchronous generator raises any other exception, |
| 730 | it is propagated to the caller of the awaitable. If the asynchronous |
| 731 | generator has already exited due to an exception or normal exit, then |
| 732 | further calls to :meth:`aclose` will return an awaitable that does nothing. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 733 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 734 | .. _primaries: |
| 735 | |
| 736 | Primaries |
| 737 | ========= |
| 738 | |
| 739 | .. index:: single: primary |
| 740 | |
| 741 | Primaries represent the most tightly bound operations of the language. Their |
| 742 | syntax is: |
| 743 | |
| 744 | .. productionlist:: |
| 745 | primary: `atom` | `attributeref` | `subscription` | `slicing` | `call` |
| 746 | |
| 747 | |
| 748 | .. _attribute-references: |
| 749 | |
| 750 | Attribute references |
| 751 | -------------------- |
| 752 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 753 | .. index:: |
| 754 | pair: attribute; reference |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 755 | single: . (dot); attribute reference |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 756 | |
| 757 | An attribute reference is a primary followed by a period and a name: |
| 758 | |
| 759 | .. productionlist:: |
| 760 | attributeref: `primary` "." `identifier` |
| 761 | |
| 762 | .. index:: |
| 763 | exception: AttributeError |
| 764 | object: module |
| 765 | object: list |
| 766 | |
| 767 | 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] | 768 | 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] | 769 | attribute whose name is the identifier. This production can be customized by |
Zachary Ware | 2f78b84 | 2014-06-03 09:32:40 -0500 | [diff] [blame] | 770 | overriding the :meth:`__getattr__` method. If this attribute is not available, |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 771 | the exception :exc:`AttributeError` is raised. Otherwise, the type and value of |
| 772 | the object produced is determined by the object. Multiple evaluations of the |
| 773 | same attribute reference may yield different objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 774 | |
| 775 | |
| 776 | .. _subscriptions: |
| 777 | |
| 778 | Subscriptions |
| 779 | ------------- |
| 780 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 781 | .. index:: |
| 782 | single: subscription |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 783 | single: [] (square brackets); subscription |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 784 | |
| 785 | .. index:: |
| 786 | object: sequence |
| 787 | object: mapping |
| 788 | object: string |
| 789 | object: tuple |
| 790 | object: list |
| 791 | object: dictionary |
| 792 | pair: sequence; item |
| 793 | |
| 794 | A subscription selects an item of a sequence (string, tuple or list) or mapping |
| 795 | (dictionary) object: |
| 796 | |
| 797 | .. productionlist:: |
| 798 | subscription: `primary` "[" `expression_list` "]" |
| 799 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 800 | The primary must evaluate to an object that supports subscription (lists or |
| 801 | dictionaries for example). User-defined objects can support subscription by |
| 802 | defining a :meth:`__getitem__` method. |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 803 | |
| 804 | 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] | 805 | |
| 806 | If the primary is a mapping, the expression list must evaluate to an object |
| 807 | whose value is one of the keys of the mapping, and the subscription selects the |
| 808 | value in the mapping that corresponds to that key. (The expression list is a |
| 809 | tuple except if it has exactly one item.) |
| 810 | |
Andrés Delfino | 4fddd4e | 2018-06-15 15:24:25 -0300 | [diff] [blame] | 811 | If the primary is a sequence, the expression list must evaluate to an integer |
Raymond Hettinger | f77c1d6 | 2010-09-15 00:09:26 +0000 | [diff] [blame] | 812 | or a slice (as discussed in the following section). |
| 813 | |
| 814 | The formal syntax makes no special provision for negative indices in |
| 815 | sequences; however, built-in sequences all provide a :meth:`__getitem__` |
| 816 | method that interprets negative indices by adding the length of the sequence |
| 817 | to the index (so that ``x[-1]`` selects the last item of ``x``). The |
| 818 | resulting value must be a nonnegative integer less than the number of items in |
| 819 | the sequence, and the subscription selects the item whose index is that value |
| 820 | (counting from zero). Since the support for negative indices and slicing |
| 821 | occurs in the object's :meth:`__getitem__` method, subclasses overriding |
| 822 | this method will need to explicitly add that support. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 823 | |
| 824 | .. index:: |
| 825 | single: character |
| 826 | pair: string; item |
| 827 | |
| 828 | A string's items are characters. A character is not a separate data type but a |
| 829 | string of exactly one character. |
| 830 | |
| 831 | |
| 832 | .. _slicings: |
| 833 | |
| 834 | Slicings |
| 835 | -------- |
| 836 | |
| 837 | .. index:: |
| 838 | single: slicing |
| 839 | single: slice |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 840 | single: : (colon); slicing |
| 841 | single: , (comma); slicing |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 842 | |
| 843 | .. index:: |
| 844 | object: sequence |
| 845 | object: string |
| 846 | object: tuple |
| 847 | object: list |
| 848 | |
| 849 | A slicing selects a range of items in a sequence object (e.g., a string, tuple |
| 850 | or list). Slicings may be used as expressions or as targets in assignment or |
| 851 | :keyword:`del` statements. The syntax for a slicing: |
| 852 | |
| 853 | .. productionlist:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 854 | slicing: `primary` "[" `slice_list` "]" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 855 | slice_list: `slice_item` ("," `slice_item`)* [","] |
Georg Brandl | cb8ecb1 | 2007-09-04 06:35:14 +0000 | [diff] [blame] | 856 | slice_item: `expression` | `proper_slice` |
Thomas Wouters | 53de190 | 2007-09-04 09:03:59 +0000 | [diff] [blame] | 857 | proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 858 | lower_bound: `expression` |
| 859 | upper_bound: `expression` |
| 860 | stride: `expression` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 861 | |
| 862 | There is ambiguity in the formal syntax here: anything that looks like an |
| 863 | expression list also looks like a slice list, so any subscription can be |
| 864 | interpreted as a slicing. Rather than further complicating the syntax, this is |
| 865 | disambiguated by defining that in this case the interpretation as a subscription |
| 866 | 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] | 867 | slice list contains no proper slice). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 868 | |
| 869 | .. index:: |
| 870 | single: start (slice object attribute) |
| 871 | single: stop (slice object attribute) |
| 872 | single: step (slice object attribute) |
| 873 | |
Georg Brandl | a4c8c47 | 2014-10-31 10:38:49 +0100 | [diff] [blame] | 874 | The semantics for a slicing are as follows. The primary is indexed (using the |
| 875 | same :meth:`__getitem__` method as |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 876 | normal subscription) with a key that is constructed from the slice list, as |
| 877 | follows. If the slice list contains at least one comma, the key is a tuple |
| 878 | containing the conversion of the slice items; otherwise, the conversion of the |
| 879 | lone slice item is the key. The conversion of a slice item that is an |
| 880 | 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] | 881 | object (see section :ref:`types`) whose :attr:`~slice.start`, |
| 882 | :attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the |
| 883 | expressions given as lower bound, upper bound and stride, respectively, |
| 884 | substituting ``None`` for missing expressions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 885 | |
| 886 | |
Chris Jerdonek | b430994 | 2012-12-25 14:54:44 -0800 | [diff] [blame] | 887 | .. index:: |
| 888 | object: callable |
| 889 | single: call |
| 890 | single: argument; call semantics |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 891 | single: () (parentheses); call |
| 892 | single: , (comma); argument list |
| 893 | single: = (equals); in function calls |
Chris Jerdonek | b430994 | 2012-12-25 14:54:44 -0800 | [diff] [blame] | 894 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 895 | .. _calls: |
| 896 | |
| 897 | Calls |
| 898 | ----- |
| 899 | |
Chris Jerdonek | b430994 | 2012-12-25 14:54:44 -0800 | [diff] [blame] | 900 | A call calls a callable object (e.g., a :term:`function`) with a possibly empty |
| 901 | series of :term:`arguments <argument>`: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 902 | |
| 903 | .. productionlist:: |
Georg Brandl | dc529c1 | 2008-09-21 17:03:29 +0000 | [diff] [blame] | 904 | call: `primary` "(" [`argument_list` [","] | `comprehension`] ")" |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 905 | argument_list: `positional_arguments` ["," `starred_and_keywords`] |
| 906 | : ["," `keywords_arguments`] |
| 907 | : | `starred_and_keywords` ["," `keywords_arguments`] |
| 908 | : | `keywords_arguments` |
| 909 | positional_arguments: ["*"] `expression` ("," ["*"] `expression`)* |
| 910 | starred_and_keywords: ("*" `expression` | `keyword_item`) |
| 911 | : ("," "*" `expression` | "," `keyword_item`)* |
| 912 | keywords_arguments: (`keyword_item` | "**" `expression`) |
Martin Panter | 7106a51 | 2016-12-24 10:20:38 +0000 | [diff] [blame] | 913 | : ("," `keyword_item` | "," "**" `expression`)* |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 914 | keyword_item: `identifier` "=" `expression` |
| 915 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 916 | An optional trailing comma may be present after the positional and keyword arguments |
| 917 | but does not affect the semantics. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 918 | |
Chris Jerdonek | b430994 | 2012-12-25 14:54:44 -0800 | [diff] [blame] | 919 | .. index:: |
| 920 | single: parameter; call semantics |
| 921 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 922 | The primary must evaluate to a callable object (user-defined functions, built-in |
| 923 | functions, methods of built-in objects, class objects, methods of class |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 924 | instances, and all objects having a :meth:`__call__` method are callable). All |
| 925 | argument expressions are evaluated before the call is attempted. Please refer |
Chris Jerdonek | b430994 | 2012-12-25 14:54:44 -0800 | [diff] [blame] | 926 | to section :ref:`function` for the syntax of formal :term:`parameter` lists. |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 927 | |
| 928 | .. XXX update with kwonly args PEP |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 929 | |
| 930 | If keyword arguments are present, they are first converted to positional |
| 931 | arguments, as follows. First, a list of unfilled slots is created for the |
| 932 | formal parameters. If there are N positional arguments, they are placed in the |
| 933 | first N slots. Next, for each keyword argument, the identifier is used to |
| 934 | determine the corresponding slot (if the identifier is the same as the first |
| 935 | formal parameter name, the first slot is used, and so on). If the slot is |
| 936 | already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of |
| 937 | the argument is placed in the slot, filling it (even if the expression is |
| 938 | ``None``, it fills the slot). When all arguments have been processed, the slots |
| 939 | that are still unfilled are filled with the corresponding default value from the |
| 940 | function definition. (Default values are calculated, once, when the function is |
| 941 | defined; thus, a mutable object such as a list or dictionary used as default |
| 942 | value will be shared by all calls that don't specify an argument value for the |
| 943 | corresponding slot; this should usually be avoided.) If there are any unfilled |
| 944 | slots for which no default value is specified, a :exc:`TypeError` exception is |
| 945 | raised. Otherwise, the list of filled slots is used as the argument list for |
| 946 | the call. |
| 947 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 948 | .. impl-detail:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 949 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 950 | An implementation may provide built-in functions whose positional parameters |
| 951 | do not have names, even if they are 'named' for the purpose of documentation, |
| 952 | 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] | 953 | 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] | 954 | parse their arguments. |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 955 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 956 | If there are more positional arguments than there are formal parameter slots, a |
| 957 | :exc:`TypeError` exception is raised, unless a formal parameter using the syntax |
| 958 | ``*identifier`` is present; in this case, that formal parameter receives a tuple |
| 959 | containing the excess positional arguments (or an empty tuple if there were no |
| 960 | excess positional arguments). |
| 961 | |
| 962 | If any keyword argument does not correspond to a formal parameter name, a |
| 963 | :exc:`TypeError` exception is raised, unless a formal parameter using the syntax |
| 964 | ``**identifier`` is present; in this case, that formal parameter receives a |
| 965 | dictionary containing the excess keyword arguments (using the keywords as keys |
| 966 | and the argument values as corresponding values), or a (new) empty dictionary if |
| 967 | there were no excess keyword arguments. |
| 968 | |
Eli Bendersky | 7bd081c | 2011-07-30 07:05:16 +0300 | [diff] [blame] | 969 | .. index:: |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 970 | single: * (asterisk); in function calls |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 971 | single: unpacking; in function calls |
Eli Bendersky | 7bd081c | 2011-07-30 07:05:16 +0300 | [diff] [blame] | 972 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 973 | If the syntax ``*expression`` appears in the function call, ``expression`` must |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 974 | evaluate to an :term:`iterable`. Elements from these iterables are |
| 975 | treated as if they were additional positional arguments. For the call |
| 976 | ``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*, |
| 977 | this is equivalent to a call with M+4 positional arguments *x1*, *x2*, |
| 978 | *y1*, ..., *yM*, *x3*, *x4*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 979 | |
Benjamin Peterson | 2d735bc | 2008-08-19 20:57:10 +0000 | [diff] [blame] | 980 | A consequence of this is that although the ``*expression`` syntax may appear |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 981 | *after* explicit keyword arguments, it is processed *before* the |
| 982 | keyword arguments (and any ``**expression`` arguments -- see below). So:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 983 | |
| 984 | >>> def f(a, b): |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 985 | ... print(a, b) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 986 | ... |
| 987 | >>> f(b=1, *(2,)) |
| 988 | 2 1 |
| 989 | >>> f(a=1, *(2,)) |
| 990 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 991 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 992 | TypeError: f() got multiple values for keyword argument 'a' |
| 993 | >>> f(1, *(2,)) |
| 994 | 1 2 |
| 995 | |
| 996 | It is unusual for both keyword arguments and the ``*expression`` syntax to be |
| 997 | used in the same call, so in practice this confusion does not arise. |
| 998 | |
Eli Bendersky | 7bd081c | 2011-07-30 07:05:16 +0300 | [diff] [blame] | 999 | .. index:: |
| 1000 | single: **; in function calls |
| 1001 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1002 | If the syntax ``**expression`` appears in the function call, ``expression`` must |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 1003 | evaluate to a :term:`mapping`, the contents of which are treated as |
| 1004 | additional keyword arguments. If a keyword is already present |
| 1005 | (as an explicit keyword argument, or from another unpacking), |
| 1006 | a :exc:`TypeError` exception is raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1007 | |
| 1008 | Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be |
| 1009 | used as positional argument slots or as keyword argument names. |
| 1010 | |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 1011 | .. versionchanged:: 3.5 |
| 1012 | Function calls accept any number of ``*`` and ``**`` unpackings, |
| 1013 | positional arguments may follow iterable unpackings (``*``), |
| 1014 | and keyword arguments may follow dictionary unpackings (``**``). |
| 1015 | Originally proposed by :pep:`448`. |
| 1016 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1017 | A call always returns some value, possibly ``None``, unless it raises an |
| 1018 | exception. How this value is computed depends on the type of the callable |
| 1019 | object. |
| 1020 | |
| 1021 | If it is--- |
| 1022 | |
| 1023 | a user-defined function: |
| 1024 | .. index:: |
| 1025 | pair: function; call |
| 1026 | triple: user-defined; function; call |
| 1027 | object: user-defined function |
| 1028 | object: function |
| 1029 | |
| 1030 | The code block for the function is executed, passing it the argument list. The |
| 1031 | first thing the code block will do is bind the formal parameters to the |
| 1032 | arguments; this is described in section :ref:`function`. When the code block |
| 1033 | executes a :keyword:`return` statement, this specifies the return value of the |
| 1034 | function call. |
| 1035 | |
| 1036 | a built-in function or method: |
| 1037 | .. index:: |
| 1038 | pair: function; call |
| 1039 | pair: built-in function; call |
| 1040 | pair: method; call |
| 1041 | pair: built-in method; call |
| 1042 | object: built-in method |
| 1043 | object: built-in function |
| 1044 | object: method |
| 1045 | object: function |
| 1046 | |
| 1047 | The result is up to the interpreter; see :ref:`built-in-funcs` for the |
| 1048 | descriptions of built-in functions and methods. |
| 1049 | |
| 1050 | a class object: |
| 1051 | .. index:: |
| 1052 | object: class |
| 1053 | pair: class object; call |
| 1054 | |
| 1055 | A new instance of that class is returned. |
| 1056 | |
| 1057 | a class instance method: |
| 1058 | .. index:: |
| 1059 | object: class instance |
| 1060 | object: instance |
| 1061 | pair: class instance; call |
| 1062 | |
| 1063 | The corresponding user-defined function is called, with an argument list that is |
| 1064 | one longer than the argument list of the call: the instance becomes the first |
| 1065 | argument. |
| 1066 | |
| 1067 | a class instance: |
| 1068 | .. index:: |
| 1069 | pair: instance; call |
| 1070 | single: __call__() (object method) |
| 1071 | |
| 1072 | The class must define a :meth:`__call__` method; the effect is then the same as |
| 1073 | if that method was called. |
| 1074 | |
| 1075 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1076 | .. index:: keyword: await |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1077 | .. _await: |
| 1078 | |
| 1079 | Await expression |
| 1080 | ================ |
| 1081 | |
| 1082 | Suspend the execution of :term:`coroutine` on an :term:`awaitable` object. |
| 1083 | Can only be used inside a :term:`coroutine function`. |
| 1084 | |
| 1085 | .. productionlist:: |
Serhiy Storchaka | c7cc985 | 2016-05-08 21:59:46 +0300 | [diff] [blame] | 1086 | await_expr: "await" `primary` |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1087 | |
| 1088 | .. versionadded:: 3.5 |
| 1089 | |
| 1090 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1091 | .. _power: |
| 1092 | |
| 1093 | The power operator |
| 1094 | ================== |
| 1095 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1096 | .. index:: |
| 1097 | pair: power; operation |
| 1098 | operator: ** |
| 1099 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1100 | The power operator binds more tightly than unary operators on its left; it binds |
| 1101 | less tightly than unary operators on its right. The syntax is: |
| 1102 | |
| 1103 | .. productionlist:: |
Andrés Delfino | caccca78 | 2018-07-07 17:24:46 -0300 | [diff] [blame] | 1104 | power: (`await_expr` | `primary`) ["**" `u_expr`] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1105 | |
| 1106 | Thus, in an unparenthesized sequence of power and unary operators, the operators |
| 1107 | 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] | 1108 | for the operands): ``-1**2`` results in ``-1``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1109 | |
| 1110 | The power operator has the same semantics as the built-in :func:`pow` function, |
| 1111 | when called with two arguments: it yields its left argument raised to the power |
| 1112 | 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] | 1113 | type, and the result is of that type. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1114 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1115 | For int operands, the result has the same type as the operands unless the second |
| 1116 | argument is negative; in that case, all arguments are converted to float and a |
| 1117 | float result is delivered. For example, ``10**2`` returns ``100``, but |
| 1118 | ``10**-2`` returns ``0.01``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1119 | |
| 1120 | Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`. |
Christian Heimes | 072c0f1 | 2008-01-03 23:01:04 +0000 | [diff] [blame] | 1121 | 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] | 1122 | number. (In earlier versions it raised a :exc:`ValueError`.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1123 | |
| 1124 | |
| 1125 | .. _unary: |
| 1126 | |
Benjamin Peterson | ba01dd9 | 2009-02-20 04:02:38 +0000 | [diff] [blame] | 1127 | Unary arithmetic and bitwise operations |
| 1128 | ======================================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1129 | |
| 1130 | .. index:: |
| 1131 | triple: unary; arithmetic; operation |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1132 | triple: unary; bitwise; operation |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1133 | |
Benjamin Peterson | ba01dd9 | 2009-02-20 04:02:38 +0000 | [diff] [blame] | 1134 | All unary arithmetic and bitwise operations have the same priority: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1135 | |
| 1136 | .. productionlist:: |
| 1137 | u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr` |
| 1138 | |
| 1139 | .. index:: |
| 1140 | single: negation |
| 1141 | single: minus |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1142 | single: operator; - (minus) |
| 1143 | single: - (minus); unary operator |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1144 | |
| 1145 | The unary ``-`` (minus) operator yields the negation of its numeric argument. |
| 1146 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1147 | .. index:: |
| 1148 | single: plus |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1149 | single: operator; + (plus) |
| 1150 | single: + (plus); unary operator |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1151 | |
| 1152 | The unary ``+`` (plus) operator yields its numeric argument unchanged. |
| 1153 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1154 | .. index:: |
| 1155 | single: inversion |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1156 | operator: ~ (tilde) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1157 | |
Georg Brandl | 95817b3 | 2008-05-11 14:30:18 +0000 | [diff] [blame] | 1158 | The unary ``~`` (invert) operator yields the bitwise inversion of its integer |
| 1159 | argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only |
| 1160 | applies to integral numbers. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1161 | |
| 1162 | .. index:: exception: TypeError |
| 1163 | |
| 1164 | In all three cases, if the argument does not have the proper type, a |
| 1165 | :exc:`TypeError` exception is raised. |
| 1166 | |
| 1167 | |
| 1168 | .. _binary: |
| 1169 | |
| 1170 | Binary arithmetic operations |
| 1171 | ============================ |
| 1172 | |
| 1173 | .. index:: triple: binary; arithmetic; operation |
| 1174 | |
| 1175 | The binary arithmetic operations have the conventional priority levels. Note |
| 1176 | that some of these operations also apply to certain non-numeric types. Apart |
| 1177 | from the power operator, there are only two levels, one for multiplicative |
| 1178 | operators and one for additive operators: |
| 1179 | |
| 1180 | .. productionlist:: |
Benjamin Peterson | d51374e | 2014-04-09 23:55:56 -0400 | [diff] [blame] | 1181 | m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` | |
Andrés Delfino | caccca78 | 2018-07-07 17:24:46 -0300 | [diff] [blame] | 1182 | : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` | |
Benjamin Peterson | d51374e | 2014-04-09 23:55:56 -0400 | [diff] [blame] | 1183 | : `m_expr` "%" `u_expr` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1184 | a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr` |
| 1185 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1186 | .. index:: |
| 1187 | single: multiplication |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1188 | operator: * (asterisk) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1189 | |
| 1190 | The ``*`` (multiplication) operator yields the product of its arguments. The |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1191 | arguments must either both be numbers, or one argument must be an integer and |
| 1192 | the other must be a sequence. In the former case, the numbers are converted to a |
| 1193 | common type and then multiplied together. In the latter case, sequence |
| 1194 | repetition is performed; a negative repetition factor yields an empty sequence. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1195 | |
Andrés Delfino | 6951186 | 2018-06-15 16:23:00 -0300 | [diff] [blame] | 1196 | .. index:: |
| 1197 | single: matrix multiplication |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1198 | operator: @ (at) |
Benjamin Peterson | d51374e | 2014-04-09 23:55:56 -0400 | [diff] [blame] | 1199 | |
| 1200 | The ``@`` (at) operator is intended to be used for matrix multiplication. No |
| 1201 | builtin Python types implement this operator. |
| 1202 | |
| 1203 | .. versionadded:: 3.5 |
| 1204 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1205 | .. index:: |
| 1206 | exception: ZeroDivisionError |
| 1207 | single: division |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1208 | operator: / (slash) |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1209 | operator: // |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1210 | |
| 1211 | The ``/`` (division) and ``//`` (floor division) operators yield the quotient of |
| 1212 | their arguments. The numeric arguments are first converted to a common type. |
Georg Brandl | 0aaae26 | 2013-10-08 21:47:18 +0200 | [diff] [blame] | 1213 | 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] | 1214 | integer; the result is that of mathematical division with the 'floor' function |
| 1215 | applied to the result. Division by zero raises the :exc:`ZeroDivisionError` |
| 1216 | exception. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1217 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1218 | .. index:: |
| 1219 | single: modulo |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1220 | operator: % (percent) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1221 | |
| 1222 | The ``%`` (modulo) operator yields the remainder from the division of the first |
| 1223 | argument by the second. The numeric arguments are first converted to a common |
| 1224 | type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The |
| 1225 | arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34`` |
| 1226 | (since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a |
| 1227 | result with the same sign as its second operand (or zero); the absolute value of |
| 1228 | the result is strictly smaller than the absolute value of the second operand |
| 1229 | [#]_. |
| 1230 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1231 | The floor division and modulo operators are connected by the following |
| 1232 | identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also |
| 1233 | connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y, |
| 1234 | x%y)``. [#]_. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1235 | |
| 1236 | In addition to performing the modulo operation on numbers, the ``%`` operator is |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1237 | also overloaded by string objects to perform old-style string formatting (also |
| 1238 | known as interpolation). The syntax for string formatting is described in the |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1239 | Python Library Reference, section :ref:`old-string-formatting`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1240 | |
| 1241 | The floor division operator, the modulo operator, and the :func:`divmod` |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1242 | function are not defined for complex numbers. Instead, convert to a floating |
| 1243 | point number using the :func:`abs` function if appropriate. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1244 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1245 | .. index:: |
| 1246 | single: addition |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1247 | single: operator; + (plus) |
| 1248 | single: + (plus); binary operator |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1249 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1250 | The ``+`` (addition) operator yields the sum of its arguments. The arguments |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 1251 | must either both be numbers or both be sequences of the same type. In the |
| 1252 | former case, the numbers are converted to a common type and then added together. |
| 1253 | In the latter case, the sequences are concatenated. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1254 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1255 | .. index:: |
| 1256 | single: subtraction |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1257 | single: operator; - (minus) |
| 1258 | single: - (minus); binary operator |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1259 | |
| 1260 | The ``-`` (subtraction) operator yields the difference of its arguments. The |
| 1261 | numeric arguments are first converted to a common type. |
| 1262 | |
| 1263 | |
| 1264 | .. _shifting: |
| 1265 | |
| 1266 | Shifting operations |
| 1267 | =================== |
| 1268 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1269 | .. index:: |
| 1270 | pair: shifting; operation |
| 1271 | operator: << |
| 1272 | operator: >> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1273 | |
| 1274 | The shifting operations have lower priority than the arithmetic operations: |
| 1275 | |
| 1276 | .. productionlist:: |
Andrés Delfino | caccca78 | 2018-07-07 17:24:46 -0300 | [diff] [blame] | 1277 | shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1278 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1279 | These operators accept integers as arguments. They shift the first argument to |
| 1280 | 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] | 1281 | |
| 1282 | .. index:: exception: ValueError |
| 1283 | |
Georg Brandl | 0aaae26 | 2013-10-08 21:47:18 +0200 | [diff] [blame] | 1284 | A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left |
| 1285 | shift by *n* bits is defined as multiplication with ``pow(2,n)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1286 | |
| 1287 | |
| 1288 | .. _bitwise: |
| 1289 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1290 | Binary bitwise operations |
| 1291 | ========================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1292 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1293 | .. index:: triple: binary; bitwise; operation |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1294 | |
| 1295 | Each of the three bitwise operations has a different priority level: |
| 1296 | |
| 1297 | .. productionlist:: |
| 1298 | and_expr: `shift_expr` | `and_expr` "&" `shift_expr` |
| 1299 | xor_expr: `and_expr` | `xor_expr` "^" `and_expr` |
| 1300 | or_expr: `xor_expr` | `or_expr` "|" `xor_expr` |
| 1301 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1302 | .. index:: |
| 1303 | pair: bitwise; and |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1304 | operator: & (ampersand) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1305 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1306 | The ``&`` operator yields the bitwise AND of its arguments, which must be |
| 1307 | integers. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1308 | |
| 1309 | .. index:: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1310 | pair: bitwise; xor |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1311 | pair: exclusive; or |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1312 | operator: ^ (caret) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1313 | |
| 1314 | The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1315 | must be integers. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1316 | |
| 1317 | .. index:: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1318 | pair: bitwise; or |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1319 | pair: inclusive; or |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1320 | operator: | (vertical bar) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1321 | |
| 1322 | The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1323 | must be integers. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1324 | |
| 1325 | |
| 1326 | .. _comparisons: |
| 1327 | |
| 1328 | Comparisons |
| 1329 | =========== |
| 1330 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1331 | .. index:: |
| 1332 | single: comparison |
| 1333 | pair: C; language |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1334 | operator: < (less) |
| 1335 | operator: > (greater) |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1336 | operator: <= |
| 1337 | operator: >= |
| 1338 | operator: == |
| 1339 | operator: != |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1340 | |
| 1341 | Unlike C, all comparison operations in Python have the same priority, which is |
| 1342 | lower than that of any arithmetic, shifting or bitwise operation. Also unlike |
| 1343 | C, expressions like ``a < b < c`` have the interpretation that is conventional |
| 1344 | in mathematics: |
| 1345 | |
| 1346 | .. productionlist:: |
Andrés Delfino | caccca78 | 2018-07-07 17:24:46 -0300 | [diff] [blame] | 1347 | comparison: `or_expr` (`comp_operator` `or_expr`)* |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1348 | comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!=" |
| 1349 | : | "is" ["not"] | ["not"] "in" |
| 1350 | |
| 1351 | Comparisons yield boolean values: ``True`` or ``False``. |
| 1352 | |
| 1353 | .. index:: pair: chaining; comparisons |
| 1354 | |
| 1355 | Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to |
| 1356 | ``x < y and y <= z``, except that ``y`` is evaluated only once (but in both |
| 1357 | cases ``z`` is not evaluated at all when ``x < y`` is found to be false). |
| 1358 | |
Guido van Rossum | 04110fb | 2007-08-24 16:32:05 +0000 | [diff] [blame] | 1359 | Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ..., |
| 1360 | *opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent |
| 1361 | to ``a op1 b and b op2 c and ... y opN z``, except that each expression is |
| 1362 | evaluated at most once. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1363 | |
Guido van Rossum | 04110fb | 2007-08-24 16:32:05 +0000 | [diff] [blame] | 1364 | 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] | 1365 | *c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not |
| 1366 | pretty). |
| 1367 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1368 | Value comparisons |
| 1369 | ----------------- |
| 1370 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1371 | The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1372 | values of two objects. The objects do not need to have the same type. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1373 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1374 | Chapter :ref:`objects` states that objects have a value (in addition to type |
| 1375 | and identity). The value of an object is a rather abstract notion in Python: |
| 1376 | For example, there is no canonical access method for an object's value. Also, |
| 1377 | there is no requirement that the value of an object should be constructed in a |
| 1378 | particular way, e.g. comprised of all its data attributes. Comparison operators |
| 1379 | implement a particular notion of what the value of an object is. One can think |
| 1380 | of them as defining the value of an object indirectly, by means of their |
| 1381 | comparison implementation. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1382 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1383 | Because all types are (direct or indirect) subtypes of :class:`object`, they |
| 1384 | inherit the default comparison behavior from :class:`object`. Types can |
| 1385 | customize their comparison behavior by implementing |
| 1386 | :dfn:`rich comparison methods` like :meth:`__lt__`, described in |
| 1387 | :ref:`customization`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1388 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1389 | The default behavior for equality comparison (``==`` and ``!=``) is based on |
| 1390 | the identity of the objects. Hence, equality comparison of instances with the |
| 1391 | same identity results in equality, and equality comparison of instances with |
| 1392 | different identities results in inequality. A motivation for this default |
| 1393 | behavior is the desire that all objects should be reflexive (i.e. ``x is y`` |
| 1394 | implies ``x == y``). |
| 1395 | |
| 1396 | A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided; |
| 1397 | an attempt raises :exc:`TypeError`. A motivation for this default behavior is |
| 1398 | the lack of a similar invariant as for equality. |
| 1399 | |
| 1400 | The behavior of the default equality comparison, that instances with different |
| 1401 | identities are always unequal, may be in contrast to what types will need that |
| 1402 | have a sensible definition of object value and value-based equality. Such |
| 1403 | types will need to customize their comparison behavior, and in fact, a number |
| 1404 | of built-in types have done that. |
| 1405 | |
| 1406 | The following list describes the comparison behavior of the most important |
| 1407 | built-in types. |
| 1408 | |
| 1409 | * Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard |
| 1410 | library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be |
| 1411 | compared within and across their types, with the restriction that complex |
| 1412 | numbers do not support order comparison. Within the limits of the types |
| 1413 | involved, they compare mathematically (algorithmically) correct without loss |
| 1414 | of precision. |
| 1415 | |
Tony Flury | ad8a000 | 2018-09-14 18:48:50 +0100 | [diff] [blame] | 1416 | The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are |
| 1417 | special. Any ordered comparison of a number to a not-a-number value is false. |
| 1418 | A counter-intuitive implication is that not-a-number values are not equal to |
| 1419 | themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3``, ``x |
| 1420 | == x``, ``x != x`` are all false. This behavior is compliant with IEEE 754. |
Raymond Hettinger | a2a08fb | 2008-11-17 22:55:16 +0000 | [diff] [blame] | 1421 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1422 | * Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be |
| 1423 | compared within and across their types. They compare lexicographically using |
| 1424 | the numeric values of their elements. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1425 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1426 | * Strings (instances of :class:`str`) compare lexicographically using the |
| 1427 | numerical Unicode code points (the result of the built-in function |
| 1428 | :func:`ord`) of their characters. [#]_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1429 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1430 | Strings and binary sequences cannot be directly compared. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1431 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1432 | * Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can |
| 1433 | be compared only within each of their types, with the restriction that ranges |
| 1434 | do not support order comparison. Equality comparison across these types |
Jim Fasarakis-Hilliard | 132ac38 | 2017-02-24 22:32:54 +0200 | [diff] [blame] | 1435 | results in inequality, and ordering comparison across these types raises |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1436 | :exc:`TypeError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1437 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1438 | Sequences compare lexicographically using comparison of corresponding |
| 1439 | elements, whereby reflexivity of the elements is enforced. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1440 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1441 | In enforcing reflexivity of elements, the comparison of collections assumes |
| 1442 | that for a collection element ``x``, ``x == x`` is always true. Based on |
| 1443 | that assumption, element identity is compared first, and element comparison |
| 1444 | is performed only for distinct elements. This approach yields the same |
| 1445 | result as a strict element comparison would, if the compared elements are |
| 1446 | reflexive. For non-reflexive elements, the result is different than for |
| 1447 | strict element comparison, and may be surprising: The non-reflexive |
| 1448 | not-a-number values for example result in the following comparison behavior |
| 1449 | when used in a list:: |
| 1450 | |
| 1451 | >>> nan = float('NaN') |
| 1452 | >>> nan is nan |
| 1453 | True |
| 1454 | >>> nan == nan |
| 1455 | False <-- the defined non-reflexive behavior of NaN |
| 1456 | >>> [nan] == [nan] |
| 1457 | True <-- list enforces reflexivity and tests identity first |
| 1458 | |
| 1459 | Lexicographical comparison between built-in collections works as follows: |
| 1460 | |
| 1461 | - For two collections to compare equal, they must be of the same type, have |
| 1462 | the same length, and each pair of corresponding elements must compare |
| 1463 | equal (for example, ``[1,2] == (1,2)`` is false because the type is not the |
| 1464 | same). |
| 1465 | |
| 1466 | - Collections that support order comparison are ordered the same as their |
| 1467 | first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same |
| 1468 | value as ``x <= y``). If a corresponding element does not exist, the |
| 1469 | shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is |
| 1470 | true). |
| 1471 | |
| 1472 | * Mappings (instances of :class:`dict`) compare equal if and only if they have |
cocoatomo | cdcac03 | 2017-03-31 14:48:49 +0900 | [diff] [blame] | 1473 | equal `(key, value)` pairs. Equality comparison of the keys and values |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1474 | enforces reflexivity. |
| 1475 | |
| 1476 | Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`. |
| 1477 | |
| 1478 | * Sets (instances of :class:`set` or :class:`frozenset`) can be compared within |
| 1479 | and across their types. |
| 1480 | |
| 1481 | They define order |
| 1482 | comparison operators to mean subset and superset tests. Those relations do |
| 1483 | not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}`` |
| 1484 | are not equal, nor subsets of one another, nor supersets of one |
Raymond Hettinger | a2a08fb | 2008-11-17 22:55:16 +0000 | [diff] [blame] | 1485 | another). Accordingly, sets are not appropriate arguments for functions |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1486 | which depend on total ordering (for example, :func:`min`, :func:`max`, and |
| 1487 | :func:`sorted` produce undefined results given a list of sets as inputs). |
Raymond Hettinger | a2a08fb | 2008-11-17 22:55:16 +0000 | [diff] [blame] | 1488 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1489 | Comparison of sets enforces reflexivity of its elements. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1490 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1491 | * Most other built-in types have no comparison methods implemented, so they |
| 1492 | inherit the default comparison behavior. |
Raymond Hettinger | a2a08fb | 2008-11-17 22:55:16 +0000 | [diff] [blame] | 1493 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1494 | User-defined classes that customize their comparison behavior should follow |
| 1495 | some consistency rules, if possible: |
| 1496 | |
| 1497 | * Equality comparison should be reflexive. |
| 1498 | In other words, identical objects should compare equal: |
| 1499 | |
| 1500 | ``x is y`` implies ``x == y`` |
| 1501 | |
| 1502 | * Comparison should be symmetric. |
| 1503 | In other words, the following expressions should have the same result: |
| 1504 | |
| 1505 | ``x == y`` and ``y == x`` |
| 1506 | |
| 1507 | ``x != y`` and ``y != x`` |
| 1508 | |
| 1509 | ``x < y`` and ``y > x`` |
| 1510 | |
| 1511 | ``x <= y`` and ``y >= x`` |
| 1512 | |
| 1513 | * Comparison should be transitive. |
| 1514 | The following (non-exhaustive) examples illustrate that: |
| 1515 | |
| 1516 | ``x > y and y > z`` implies ``x > z`` |
| 1517 | |
| 1518 | ``x < y and y <= z`` implies ``x < z`` |
| 1519 | |
| 1520 | * Inverse comparison should result in the boolean negation. |
| 1521 | In other words, the following expressions should have the same result: |
| 1522 | |
| 1523 | ``x == y`` and ``not x != y`` |
| 1524 | |
| 1525 | ``x < y`` and ``not x >= y`` (for total ordering) |
| 1526 | |
| 1527 | ``x > y`` and ``not x <= y`` (for total ordering) |
| 1528 | |
| 1529 | The last two expressions apply to totally ordered collections (e.g. to |
| 1530 | sequences, but not to sets or mappings). See also the |
| 1531 | :func:`~functools.total_ordering` decorator. |
| 1532 | |
Martin Panter | 8dbb0ca | 2017-01-29 10:00:23 +0000 | [diff] [blame] | 1533 | * The :func:`hash` result should be consistent with equality. |
| 1534 | Objects that are equal should either have the same hash value, |
| 1535 | or be marked as unhashable. |
| 1536 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1537 | Python does not enforce these consistency rules. In fact, the not-a-number |
| 1538 | values are an example for not following these rules. |
| 1539 | |
| 1540 | |
| 1541 | .. _in: |
| 1542 | .. _not in: |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 1543 | .. _membership-test-details: |
| 1544 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1545 | Membership test operations |
| 1546 | -------------------------- |
| 1547 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1548 | The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in |
Amit Kumar | 0ae7c8b | 2017-03-28 19:43:01 +0530 | [diff] [blame] | 1549 | s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise. |
| 1550 | ``x not in s`` returns the negation of ``x in s``. All built-in sequences and |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 1551 | set types support this as well as dictionary, for which :keyword:`!in` tests |
Amit Kumar | 0ae7c8b | 2017-03-28 19:43:01 +0530 | [diff] [blame] | 1552 | whether the dictionary has a given key. For container types such as list, tuple, |
| 1553 | set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent |
Stefan Krah | c8bdc01 | 2010-04-01 10:34:09 +0000 | [diff] [blame] | 1554 | to ``any(x is e or x == e for e in y)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1555 | |
Amit Kumar | 0ae7c8b | 2017-03-28 19:43:01 +0530 | [diff] [blame] | 1556 | For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1557 | substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are |
| 1558 | always considered to be a substring of any other string, so ``"" in "abc"`` will |
| 1559 | return ``True``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1560 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1561 | For user-defined classes which define the :meth:`__contains__` method, ``x in |
Amit Kumar | 0ae7c8b | 2017-03-28 19:43:01 +0530 | [diff] [blame] | 1562 | y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and |
| 1563 | ``False`` otherwise. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1564 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 1565 | For user-defined classes which do not define :meth:`__contains__` but do define |
Amit Kumar | 0ae7c8b | 2017-03-28 19:43:01 +0530 | [diff] [blame] | 1566 | :meth:`__iter__`, ``x in y`` is ``True`` if some value ``z`` with ``x == z`` is |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 1567 | produced while iterating over ``y``. If an exception is raised during the |
| 1568 | iteration, it is as if :keyword:`in` raised that exception. |
| 1569 | |
| 1570 | Lastly, the old-style iteration protocol is tried: if a class defines |
Amit Kumar | 0ae7c8b | 2017-03-28 19:43:01 +0530 | [diff] [blame] | 1571 | :meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1572 | 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] | 1573 | 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] | 1574 | if :keyword:`in` raised that exception). |
| 1575 | |
| 1576 | .. index:: |
| 1577 | operator: in |
| 1578 | operator: not in |
| 1579 | pair: membership; test |
| 1580 | object: sequence |
| 1581 | |
| 1582 | The operator :keyword:`not in` is defined to have the inverse true value of |
| 1583 | :keyword:`in`. |
| 1584 | |
| 1585 | .. index:: |
| 1586 | operator: is |
| 1587 | operator: is not |
| 1588 | pair: identity; test |
| 1589 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1590 | |
| 1591 | .. _is: |
| 1592 | .. _is not: |
| 1593 | |
| 1594 | Identity comparisons |
| 1595 | -------------------- |
| 1596 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1597 | The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x |
Raymond Hettinger | 06e18a7 | 2016-09-11 17:23:49 -0700 | [diff] [blame] | 1598 | is y`` is true if and only if *x* and *y* are the same object. Object identity |
| 1599 | is determined using the :meth:`id` function. ``x is not y`` yields the inverse |
| 1600 | truth value. [#]_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1601 | |
| 1602 | |
| 1603 | .. _booleans: |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 1604 | .. _and: |
| 1605 | .. _or: |
| 1606 | .. _not: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1607 | |
| 1608 | Boolean operations |
| 1609 | ================== |
| 1610 | |
| 1611 | .. index:: |
| 1612 | pair: Conditional; expression |
| 1613 | pair: Boolean; operation |
| 1614 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1615 | .. productionlist:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1616 | or_test: `and_test` | `or_test` "or" `and_test` |
| 1617 | and_test: `not_test` | `and_test` "and" `not_test` |
| 1618 | not_test: `comparison` | "not" `not_test` |
| 1619 | |
| 1620 | In the context of Boolean operations, and also when expressions are used by |
| 1621 | control flow statements, the following values are interpreted as false: |
| 1622 | ``False``, ``None``, numeric zero of all types, and empty strings and containers |
| 1623 | (including strings, tuples, lists, dictionaries, sets and frozensets). All |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1624 | other values are interpreted as true. User-defined objects can customize their |
| 1625 | truth value by providing a :meth:`__bool__` method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1626 | |
| 1627 | .. index:: operator: not |
| 1628 | |
| 1629 | The operator :keyword:`not` yields ``True`` if its argument is false, ``False`` |
| 1630 | otherwise. |
| 1631 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1632 | .. index:: operator: and |
| 1633 | |
| 1634 | The expression ``x and y`` first evaluates *x*; if *x* is false, its value is |
| 1635 | returned; otherwise, *y* is evaluated and the resulting value is returned. |
| 1636 | |
| 1637 | .. index:: operator: or |
| 1638 | |
| 1639 | The expression ``x or y`` first evaluates *x*; if *x* is true, its value is |
| 1640 | returned; otherwise, *y* is evaluated and the resulting value is returned. |
| 1641 | |
Andre Delfino | 55f41e4 | 2018-12-05 16:45:30 -0300 | [diff] [blame] | 1642 | Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1643 | they return to ``False`` and ``True``, but rather return the last evaluated |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1644 | 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] | 1645 | 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] | 1646 | the desired value. Because :keyword:`not` has to create a new value, it |
| 1647 | returns a boolean value regardless of the type of its argument |
| 1648 | (for example, ``not 'foo'`` produces ``False`` rather than ``''``.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1649 | |
| 1650 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 1651 | .. _if_expr: |
| 1652 | |
Alexander Belopolsky | 50ba19e | 2010-12-15 19:47:37 +0000 | [diff] [blame] | 1653 | Conditional expressions |
Georg Brandl | 93dc9eb | 2010-03-14 10:56:14 +0000 | [diff] [blame] | 1654 | ======================= |
| 1655 | |
Georg Brandl | 93dc9eb | 2010-03-14 10:56:14 +0000 | [diff] [blame] | 1656 | .. index:: |
| 1657 | pair: conditional; expression |
| 1658 | pair: ternary; operator |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1659 | single: if; conditional expression |
| 1660 | single: else; conditional expression |
Georg Brandl | 93dc9eb | 2010-03-14 10:56:14 +0000 | [diff] [blame] | 1661 | |
| 1662 | .. productionlist:: |
| 1663 | conditional_expression: `or_test` ["if" `or_test` "else" `expression`] |
Georg Brandl | 242e6a0 | 2013-10-06 10:28:39 +0200 | [diff] [blame] | 1664 | expression: `conditional_expression` | `lambda_expr` |
| 1665 | expression_nocond: `or_test` | `lambda_expr_nocond` |
Georg Brandl | 93dc9eb | 2010-03-14 10:56:14 +0000 | [diff] [blame] | 1666 | |
| 1667 | Conditional expressions (sometimes called a "ternary operator") have the lowest |
| 1668 | priority of all Python operations. |
| 1669 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 1670 | The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*. |
| 1671 | 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] | 1672 | evaluated and its value is returned. |
| 1673 | |
| 1674 | See :pep:`308` for more details about conditional expressions. |
| 1675 | |
| 1676 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1677 | .. _lambdas: |
Georg Brandl | c4f8b24 | 2009-04-10 08:17:21 +0000 | [diff] [blame] | 1678 | .. _lambda: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1679 | |
| 1680 | Lambdas |
| 1681 | ======= |
| 1682 | |
| 1683 | .. index:: |
| 1684 | pair: lambda; expression |
| 1685 | pair: lambda; form |
| 1686 | pair: anonymous; function |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1687 | single: : (colon); lambda expression |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1688 | |
| 1689 | .. productionlist:: |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1690 | lambda_expr: "lambda" [`parameter_list`] ":" `expression` |
| 1691 | lambda_expr_nocond: "lambda" [`parameter_list`] ":" `expression_nocond` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1692 | |
Zachary Ware | 2f78b84 | 2014-06-03 09:32:40 -0500 | [diff] [blame] | 1693 | Lambda expressions (sometimes called lambda forms) are used to create anonymous |
Andrés Delfino | 268cc7c | 2018-05-22 02:57:45 -0300 | [diff] [blame] | 1694 | functions. The expression ``lambda parameters: expression`` yields a function |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 1695 | object. The unnamed object behaves like a function object defined with: |
| 1696 | |
| 1697 | .. code-block:: none |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1698 | |
Andrés Delfino | 268cc7c | 2018-05-22 02:57:45 -0300 | [diff] [blame] | 1699 | def <lambda>(parameters): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1700 | return expression |
| 1701 | |
| 1702 | See section :ref:`function` for the syntax of parameter lists. Note that |
Georg Brandl | 242e6a0 | 2013-10-06 10:28:39 +0200 | [diff] [blame] | 1703 | functions created with lambda expressions cannot contain statements or |
| 1704 | annotations. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1705 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1706 | |
| 1707 | .. _exprlists: |
| 1708 | |
| 1709 | Expression lists |
| 1710 | ================ |
| 1711 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1712 | .. index:: |
| 1713 | pair: expression; list |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1714 | single: , (comma); expression list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1715 | |
| 1716 | .. productionlist:: |
Andrés Delfino | caccca78 | 2018-07-07 17:24:46 -0300 | [diff] [blame] | 1717 | expression_list: `expression` ("," `expression`)* [","] |
| 1718 | starred_list: `starred_item` ("," `starred_item`)* [","] |
| 1719 | starred_expression: `expression` | (`starred_item` ",")* [`starred_item`] |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 1720 | starred_item: `expression` | "*" `or_expr` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1721 | |
| 1722 | .. index:: object: tuple |
| 1723 | |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 1724 | Except when part of a list or set display, an expression list |
| 1725 | containing at least one comma yields a tuple. The length of |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1726 | the tuple is the number of expressions in the list. The expressions are |
| 1727 | evaluated from left to right. |
| 1728 | |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 1729 | .. index:: |
| 1730 | pair: iterable; unpacking |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1731 | single: * (asterisk); in expression lists |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 1732 | |
| 1733 | An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be |
| 1734 | an :term:`iterable`. The iterable is expanded into a sequence of items, |
| 1735 | which are included in the new tuple, list, or set, at the site of |
| 1736 | the unpacking. |
| 1737 | |
| 1738 | .. versionadded:: 3.5 |
| 1739 | Iterable unpacking in expression lists, originally proposed by :pep:`448`. |
| 1740 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1741 | .. index:: pair: trailing; comma |
| 1742 | |
| 1743 | The trailing comma is required only to create a single tuple (a.k.a. a |
| 1744 | *singleton*); it is optional in all other cases. A single expression without a |
| 1745 | trailing comma doesn't create a tuple, but rather yields the value of that |
| 1746 | expression. (To create an empty tuple, use an empty pair of parentheses: |
| 1747 | ``()``.) |
| 1748 | |
| 1749 | |
| 1750 | .. _evalorder: |
| 1751 | |
| 1752 | Evaluation order |
| 1753 | ================ |
| 1754 | |
| 1755 | .. index:: pair: evaluation; order |
| 1756 | |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1757 | Python evaluates expressions from left to right. Notice that while evaluating |
| 1758 | 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] | 1759 | |
| 1760 | In the following lines, expressions will be evaluated in the arithmetic order of |
| 1761 | their suffixes:: |
| 1762 | |
| 1763 | expr1, expr2, expr3, expr4 |
| 1764 | (expr1, expr2, expr3, expr4) |
| 1765 | {expr1: expr2, expr3: expr4} |
| 1766 | expr1 + expr2 * (expr3 - expr4) |
Georg Brandl | 734e268 | 2008-08-12 08:18:18 +0000 | [diff] [blame] | 1767 | expr1(expr2, expr3, *expr4, **expr5) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1768 | expr3, expr4 = expr1, expr2 |
| 1769 | |
| 1770 | |
| 1771 | .. _operator-summary: |
| 1772 | |
Ezio Melotti | 9f929bb | 2012-12-25 15:45:15 +0200 | [diff] [blame] | 1773 | Operator precedence |
| 1774 | =================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1775 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1776 | .. index:: |
| 1777 | pair: operator; precedence |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1778 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 1779 | The following table summarizes the operator precedence in Python, from lowest |
Georg Brandl | 96593ed | 2007-09-07 14:15:41 +0000 | [diff] [blame] | 1780 | precedence (least binding) to highest precedence (most binding). Operators in |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1781 | the same box have the same precedence. Unless the syntax is explicitly given, |
| 1782 | 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] | 1783 | exponentiation, which groups from right to left). |
| 1784 | |
| 1785 | Note that comparisons, membership tests, and identity tests, all have the same |
| 1786 | precedence and have a left-to-right chaining feature as described in the |
| 1787 | :ref:`comparisons` section. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1788 | |
Benjamin Peterson | ba01dd9 | 2009-02-20 04:02:38 +0000 | [diff] [blame] | 1789 | |
| 1790 | +-----------------------------------------------+-------------------------------------+ |
| 1791 | | Operator | Description | |
| 1792 | +===============================================+=====================================+ |
| 1793 | | :keyword:`lambda` | Lambda expression | |
| 1794 | +-----------------------------------------------+-------------------------------------+ |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 1795 | | :keyword:`if <if_expr>` -- :keyword:`!else` | Conditional expression | |
Georg Brandl | 93dc9eb | 2010-03-14 10:56:14 +0000 | [diff] [blame] | 1796 | +-----------------------------------------------+-------------------------------------+ |
Benjamin Peterson | ba01dd9 | 2009-02-20 04:02:38 +0000 | [diff] [blame] | 1797 | | :keyword:`or` | Boolean OR | |
| 1798 | +-----------------------------------------------+-------------------------------------+ |
| 1799 | | :keyword:`and` | Boolean AND | |
| 1800 | +-----------------------------------------------+-------------------------------------+ |
Ezio Melotti | 9f929bb | 2012-12-25 15:45:15 +0200 | [diff] [blame] | 1801 | | :keyword:`not` ``x`` | Boolean NOT | |
Benjamin Peterson | ba01dd9 | 2009-02-20 04:02:38 +0000 | [diff] [blame] | 1802 | +-----------------------------------------------+-------------------------------------+ |
Ezio Melotti | 9f929bb | 2012-12-25 15:45:15 +0200 | [diff] [blame] | 1803 | | :keyword:`in`, :keyword:`not in`, | Comparisons, including membership | |
Georg Brandl | 44ea77b | 2013-03-28 13:28:44 +0100 | [diff] [blame] | 1804 | | :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests | |
Georg Brandl | a5ebc26 | 2009-06-03 07:26:22 +0000 | [diff] [blame] | 1805 | | ``<=``, ``>``, ``>=``, ``!=``, ``==`` | | |
Benjamin Peterson | ba01dd9 | 2009-02-20 04:02:38 +0000 | [diff] [blame] | 1806 | +-----------------------------------------------+-------------------------------------+ |
| 1807 | | ``|`` | Bitwise OR | |
| 1808 | +-----------------------------------------------+-------------------------------------+ |
| 1809 | | ``^`` | Bitwise XOR | |
| 1810 | +-----------------------------------------------+-------------------------------------+ |
| 1811 | | ``&`` | Bitwise AND | |
| 1812 | +-----------------------------------------------+-------------------------------------+ |
| 1813 | | ``<<``, ``>>`` | Shifts | |
| 1814 | +-----------------------------------------------+-------------------------------------+ |
| 1815 | | ``+``, ``-`` | Addition and subtraction | |
| 1816 | +-----------------------------------------------+-------------------------------------+ |
Benjamin Peterson | d51374e | 2014-04-09 23:55:56 -0400 | [diff] [blame] | 1817 | | ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix | |
svelankar | 9b47af6 | 2017-09-17 20:56:16 -0400 | [diff] [blame] | 1818 | | | multiplication, division, floor | |
| 1819 | | | division, remainder [#]_ | |
Benjamin Peterson | ba01dd9 | 2009-02-20 04:02:38 +0000 | [diff] [blame] | 1820 | +-----------------------------------------------+-------------------------------------+ |
| 1821 | | ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT | |
| 1822 | +-----------------------------------------------+-------------------------------------+ |
| 1823 | | ``**`` | Exponentiation [#]_ | |
| 1824 | +-----------------------------------------------+-------------------------------------+ |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1825 | | :keyword:`await` ``x`` | Await expression | |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1826 | +-----------------------------------------------+-------------------------------------+ |
Benjamin Peterson | ba01dd9 | 2009-02-20 04:02:38 +0000 | [diff] [blame] | 1827 | | ``x[index]``, ``x[index:index]``, | Subscription, slicing, | |
| 1828 | | ``x(arguments...)``, ``x.attribute`` | call, attribute reference | |
| 1829 | +-----------------------------------------------+-------------------------------------+ |
| 1830 | | ``(expressions...)``, | Binding or tuple display, | |
| 1831 | | ``[expressions...]``, | list display, | |
Ezio Melotti | 9f929bb | 2012-12-25 15:45:15 +0200 | [diff] [blame] | 1832 | | ``{key: value...}``, | dictionary display, | |
Brett Cannon | 925914f | 2010-11-21 19:58:24 +0000 | [diff] [blame] | 1833 | | ``{expressions...}`` | set display | |
Benjamin Peterson | ba01dd9 | 2009-02-20 04:02:38 +0000 | [diff] [blame] | 1834 | +-----------------------------------------------+-------------------------------------+ |
| 1835 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1836 | |
| 1837 | .. rubric:: Footnotes |
| 1838 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1839 | .. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be |
| 1840 | true numerically due to roundoff. For example, and assuming a platform on which |
| 1841 | a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 % |
| 1842 | 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] | 1843 | 1e100``, which is numerically exactly equal to ``1e100``. The function |
| 1844 | :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] | 1845 | first argument instead, and so returns ``-1e-100`` in this case. Which approach |
| 1846 | is more appropriate depends on the application. |
| 1847 | |
| 1848 | .. [#] 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] | 1849 | ``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] | 1850 | cases, Python returns the latter result, in order to preserve that |
| 1851 | ``divmod(x,y)[0] * y + x % y`` be very close to ``x``. |
| 1852 | |
Martin Panter | aa0da86 | 2015-09-23 05:28:13 +0000 | [diff] [blame] | 1853 | .. [#] The Unicode standard distinguishes between :dfn:`code points` |
| 1854 | (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A"). |
| 1855 | While most abstract characters in Unicode are only represented using one |
| 1856 | code point, there is a number of abstract characters that can in addition be |
| 1857 | represented using a sequence of more than one code point. For example, the |
| 1858 | abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented |
| 1859 | as a single :dfn:`precomposed character` at code position U+00C7, or as a |
| 1860 | sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL |
| 1861 | LETTER C), followed by a :dfn:`combining character` at code position U+0327 |
| 1862 | (COMBINING CEDILLA). |
| 1863 | |
| 1864 | The comparison operators on strings compare at the level of Unicode code |
| 1865 | points. This may be counter-intuitive to humans. For example, |
| 1866 | ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings |
| 1867 | represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA". |
| 1868 | |
| 1869 | To compare strings at the level of abstract characters (that is, in a way |
| 1870 | intuitive to humans), use :func:`unicodedata.normalize`. |
Guido van Rossum | da27fd2 | 2007-08-17 00:24:54 +0000 | [diff] [blame] | 1871 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1872 | .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 1873 | descriptors, you may notice seemingly unusual behaviour in certain uses of |
| 1874 | the :keyword:`is` operator, like those involving comparisons between instance |
| 1875 | methods, or constants. Check their documentation for more info. |
Benjamin Peterson | ba01dd9 | 2009-02-20 04:02:38 +0000 | [diff] [blame] | 1876 | |
Georg Brandl | 063f237 | 2010-12-01 15:32:43 +0000 | [diff] [blame] | 1877 | .. [#] The ``%`` operator is also used for string formatting; the same |
| 1878 | precedence applies. |
Georg Brandl | f1d633c | 2010-09-20 06:29:01 +0000 | [diff] [blame] | 1879 | |
Benjamin Peterson | ba01dd9 | 2009-02-20 04:02:38 +0000 | [diff] [blame] | 1880 | .. [#] The power operator ``**`` binds less tightly than an arithmetic or |
| 1881 | bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. |