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