Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | .. _compound: |
| 2 | |
| 3 | ******************* |
| 4 | Compound statements |
| 5 | ******************* |
| 6 | |
| 7 | .. index:: pair: compound; statement |
| 8 | |
| 9 | Compound statements contain (groups of) other statements; they affect or control |
| 10 | the execution of those other statements in some way. In general, compound |
| 11 | statements span multiple lines, although in simple incarnations a whole compound |
| 12 | statement may be contained in one line. |
| 13 | |
| 14 | The :keyword:`if`, :keyword:`while` and :keyword:`for` statements implement |
| 15 | traditional control flow constructs. :keyword:`try` specifies exception |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 16 | handlers and/or cleanup code for a group of statements, while the |
| 17 | :keyword:`with` statement allows the execution of initialization and |
| 18 | finalization code around a block of code. Function and class definitions are |
| 19 | also syntactically compound statements. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 20 | |
| 21 | .. index:: |
| 22 | single: clause |
| 23 | single: suite |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 24 | single: ; (semicolon) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 25 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 26 | A compound statement consists of one or more 'clauses.' A clause consists of a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 27 | header and a 'suite.' The clause headers of a particular compound statement are |
| 28 | all at the same indentation level. Each clause header begins with a uniquely |
| 29 | identifying keyword and ends with a colon. A suite is a group of statements |
| 30 | controlled by a clause. A suite can be one or more semicolon-separated simple |
| 31 | statements on the same line as the header, following the header's colon, or it |
| 32 | can be one or more indented statements on subsequent lines. Only the latter |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 33 | form of a suite can contain nested compound statements; the following is illegal, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 34 | mostly because it wouldn't be clear to which :keyword:`if` clause a following |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 35 | :keyword:`else` clause would belong:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 36 | |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 37 | if test1: if test2: print(x) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 38 | |
| 39 | Also note that the semicolon binds tighter than the colon in this context, so |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 40 | that in the following example, either all or none of the :func:`print` calls are |
| 41 | executed:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 42 | |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 43 | if x < y < z: print(x); print(y); print(z) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 44 | |
| 45 | Summarizing: |
| 46 | |
Victor Stinner | 8af239e | 2020-09-18 09:10:15 +0200 | [diff] [blame] | 47 | |
| 48 | .. productionlist:: python-grammar |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 49 | compound_stmt: `if_stmt` |
| 50 | : | `while_stmt` |
| 51 | : | `for_stmt` |
| 52 | : | `try_stmt` |
| 53 | : | `with_stmt` |
Daniel F Moisset | a22bca6 | 2021-03-01 04:08:38 +0000 | [diff] [blame] | 54 | : | `match_stmt` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 55 | : | `funcdef` |
| 56 | : | `classdef` |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 57 | : | `async_with_stmt` |
| 58 | : | `async_for_stmt` |
| 59 | : | `async_funcdef` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 60 | suite: `stmt_list` NEWLINE | NEWLINE INDENT `statement`+ DEDENT |
| 61 | statement: `stmt_list` NEWLINE | `compound_stmt` |
| 62 | stmt_list: `simple_stmt` (";" `simple_stmt`)* [";"] |
| 63 | |
| 64 | .. index:: |
| 65 | single: NEWLINE token |
| 66 | single: DEDENT token |
| 67 | pair: dangling; else |
| 68 | |
| 69 | Note that statements always end in a ``NEWLINE`` possibly followed by a |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 70 | ``DEDENT``. Also note that optional continuation clauses always begin with a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 71 | keyword that cannot start a statement, thus there are no ambiguities (the |
| 72 | 'dangling :keyword:`else`' problem is solved in Python by requiring nested |
| 73 | :keyword:`if` statements to be indented). |
| 74 | |
| 75 | The formatting of the grammar rules in the following sections places each clause |
| 76 | on a separate line for clarity. |
| 77 | |
| 78 | |
| 79 | .. _if: |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 80 | .. _elif: |
| 81 | .. _else: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 82 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 83 | The :keyword:`!if` statement |
| 84 | ============================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 85 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 86 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 87 | ! statement: if |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 88 | keyword: elif |
| 89 | keyword: else |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 90 | single: : (colon); compound statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 91 | |
| 92 | The :keyword:`if` statement is used for conditional execution: |
| 93 | |
Victor Stinner | 8af239e | 2020-09-18 09:10:15 +0200 | [diff] [blame] | 94 | .. productionlist:: python-grammar |
Brandt Bucher | 8bae219 | 2020-03-05 21:19:22 -0800 | [diff] [blame] | 95 | if_stmt: "if" `assignment_expression` ":" `suite` |
| 96 | : ("elif" `assignment_expression` ":" `suite`)* |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 97 | : ["else" ":" `suite`] |
| 98 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 99 | It selects exactly one of the suites by evaluating the expressions one by one |
| 100 | until one is found to be true (see section :ref:`booleans` for the definition of |
| 101 | true and false); then that suite is executed (and no other part of the |
| 102 | :keyword:`if` statement is executed or evaluated). If all expressions are |
| 103 | false, the suite of the :keyword:`else` clause, if present, is executed. |
| 104 | |
| 105 | |
| 106 | .. _while: |
| 107 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 108 | The :keyword:`!while` statement |
| 109 | =============================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 110 | |
| 111 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 112 | ! statement: while |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 113 | keyword: else |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 114 | pair: loop; statement |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 115 | single: : (colon); compound statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 116 | |
| 117 | The :keyword:`while` statement is used for repeated execution as long as an |
| 118 | expression is true: |
| 119 | |
Victor Stinner | 8af239e | 2020-09-18 09:10:15 +0200 | [diff] [blame] | 120 | .. productionlist:: python-grammar |
Brandt Bucher | 8bae219 | 2020-03-05 21:19:22 -0800 | [diff] [blame] | 121 | while_stmt: "while" `assignment_expression` ":" `suite` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 122 | : ["else" ":" `suite`] |
| 123 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 124 | This repeatedly tests the expression and, if it is true, executes the first |
| 125 | suite; if the expression is false (which may be the first time it is tested) the |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 126 | suite of the :keyword:`!else` clause, if present, is executed and the loop |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 127 | terminates. |
| 128 | |
| 129 | .. index:: |
| 130 | statement: break |
| 131 | statement: continue |
| 132 | |
| 133 | A :keyword:`break` statement executed in the first suite terminates the loop |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 134 | without executing the :keyword:`!else` clause's suite. A :keyword:`continue` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 135 | statement executed in the first suite skips the rest of the suite and goes back |
| 136 | to testing the expression. |
| 137 | |
| 138 | |
| 139 | .. _for: |
| 140 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 141 | The :keyword:`!for` statement |
| 142 | ============================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 143 | |
| 144 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 145 | ! statement: for |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 146 | keyword: in |
| 147 | keyword: else |
| 148 | pair: target; list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 149 | pair: loop; statement |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 150 | object: sequence |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 151 | single: : (colon); compound statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 152 | |
| 153 | The :keyword:`for` statement is used to iterate over the elements of a sequence |
| 154 | (such as a string, tuple or list) or other iterable object: |
| 155 | |
Victor Stinner | 8af239e | 2020-09-18 09:10:15 +0200 | [diff] [blame] | 156 | .. productionlist:: python-grammar |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 157 | for_stmt: "for" `target_list` "in" `expression_list` ":" `suite` |
| 158 | : ["else" ":" `suite`] |
| 159 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 160 | The expression list is evaluated once; it should yield an iterable object. An |
| 161 | iterator is created for the result of the ``expression_list``. The suite is |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 162 | then executed once for each item provided by the iterator, in the order returned |
| 163 | by the iterator. Each item in turn is assigned to the target list using the |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 164 | standard rules for assignments (see :ref:`assignment`), and then the suite is |
| 165 | executed. When the items are exhausted (which is immediately when the sequence |
| 166 | is empty or an iterator raises a :exc:`StopIteration` exception), the suite in |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 167 | the :keyword:`!else` clause, if present, is executed, and the loop terminates. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 168 | |
| 169 | .. index:: |
| 170 | statement: break |
| 171 | statement: continue |
| 172 | |
| 173 | A :keyword:`break` statement executed in the first suite terminates the loop |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 174 | without executing the :keyword:`!else` clause's suite. A :keyword:`continue` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 175 | statement executed in the first suite skips the rest of the suite and continues |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 176 | with the next item, or with the :keyword:`!else` clause if there is no next |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 177 | item. |
| 178 | |
Andrés Delfino | e42b705 | 2018-07-26 12:35:23 -0300 | [diff] [blame] | 179 | The for-loop makes assignments to the variables in the target list. |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 180 | This overwrites all previous assignments to those variables including |
| 181 | those made in the suite of the for-loop:: |
| 182 | |
| 183 | for i in range(10): |
| 184 | print(i) |
| 185 | i = 5 # this will not affect the for-loop |
Zachary Ware | 2f78b84 | 2014-06-03 09:32:40 -0500 | [diff] [blame] | 186 | # because i will be overwritten with the next |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 187 | # index in the range |
| 188 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 189 | |
| 190 | .. index:: |
| 191 | builtin: range |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 192 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 193 | Names in the target list are not deleted when the loop is finished, but if the |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 194 | sequence is empty, they will not have been assigned to at all by the loop. Hint: |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 195 | the built-in function :func:`range` returns an iterator of integers suitable to |
Benjamin Peterson | 3db5e7b | 2009-06-03 03:13:30 +0000 | [diff] [blame] | 196 | emulate the effect of Pascal's ``for i := a to b do``; e.g., ``list(range(3))`` |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 197 | returns the list ``[0, 1, 2]``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 198 | |
Georg Brandl | e720c0a | 2009-04-27 16:20:50 +0000 | [diff] [blame] | 199 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 200 | |
| 201 | .. index:: |
| 202 | single: loop; over mutable sequence |
| 203 | single: mutable sequence; loop over |
| 204 | |
| 205 | There is a subtlety when the sequence is being modified by the loop (this can |
Andrés Delfino | 6921ef7 | 2018-07-30 15:44:35 -0300 | [diff] [blame] | 206 | only occur for mutable sequences, e.g. lists). An internal counter is used |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 207 | to keep track of which item is used next, and this is incremented on each |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 208 | iteration. When this counter has reached the length of the sequence the loop |
| 209 | terminates. This means that if the suite deletes the current (or a previous) |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 210 | item from the sequence, the next item will be skipped (since it gets the |
| 211 | index of the current item which has already been treated). Likewise, if the |
| 212 | suite inserts an item in the sequence before the current item, the current |
| 213 | item will be treated again the next time through the loop. This can lead to |
| 214 | nasty bugs that can be avoided by making a temporary copy using a slice of |
| 215 | the whole sequence, e.g., :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 216 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 217 | for x in a[:]: |
| 218 | if x < 0: a.remove(x) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 219 | |
| 220 | |
| 221 | .. _try: |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 222 | .. _except: |
| 223 | .. _finally: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 224 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 225 | The :keyword:`!try` statement |
| 226 | ============================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 227 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 228 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 229 | ! statement: try |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 230 | keyword: except |
| 231 | keyword: finally |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 232 | keyword: else |
| 233 | keyword: as |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 234 | single: : (colon); compound statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 235 | |
| 236 | The :keyword:`try` statement specifies exception handlers and/or cleanup code |
| 237 | for a group of statements: |
| 238 | |
Victor Stinner | 8af239e | 2020-09-18 09:10:15 +0200 | [diff] [blame] | 239 | .. productionlist:: python-grammar |
Andrés Delfino | caccca78 | 2018-07-07 17:24:46 -0300 | [diff] [blame] | 240 | try_stmt: `try1_stmt` | `try2_stmt` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 241 | try1_stmt: "try" ":" `suite` |
Terry Jan Reedy | 65e3ecb | 2014-08-23 19:29:47 -0400 | [diff] [blame] | 242 | : ("except" [`expression` ["as" `identifier`]] ":" `suite`)+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 243 | : ["else" ":" `suite`] |
| 244 | : ["finally" ":" `suite`] |
| 245 | try2_stmt: "try" ":" `suite` |
| 246 | : "finally" ":" `suite` |
| 247 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 248 | |
| 249 | The :keyword:`except` clause(s) specify one or more exception handlers. When no |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 250 | exception occurs in the :keyword:`try` clause, no exception handler is executed. |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 251 | When an exception occurs in the :keyword:`!try` suite, a search for an exception |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 252 | handler is started. This search inspects the except clauses in turn until one |
| 253 | is found that matches the exception. An expression-less except clause, if |
| 254 | present, must be last; it matches any exception. For an except clause with an |
| 255 | expression, that expression is evaluated, and the clause matches the exception |
| 256 | if the resulting object is "compatible" with the exception. An object is |
| 257 | compatible with an exception if it is the class or a base class of the exception |
Colin Watson | c95f8bc | 2020-12-20 18:24:10 +0000 | [diff] [blame] | 258 | object, or a tuple containing an item that is the class or a base class of |
| 259 | the exception object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 260 | |
| 261 | If no except clause matches the exception, the search for an exception handler |
| 262 | continues in the surrounding code and on the invocation stack. [#]_ |
| 263 | |
| 264 | If the evaluation of an expression in the header of an except clause raises an |
| 265 | exception, the original search for a handler is canceled and a search starts for |
| 266 | the new exception in the surrounding code and on the call stack (it is treated |
| 267 | as if the entire :keyword:`try` statement raised the exception). |
| 268 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 269 | .. index:: single: as; except clause |
| 270 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 271 | When a matching except clause is found, the exception is assigned to the target |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 272 | specified after the :keyword:`!as` keyword in that except clause, if present, and |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 273 | the except clause's suite is executed. All except clauses must have an |
| 274 | executable block. When the end of this block is reached, execution continues |
| 275 | normally after the entire try statement. (This means that if two nested |
| 276 | handlers exist for the same exception, and the exception occurs in the try |
| 277 | clause of the inner handler, the outer handler will not handle the exception.) |
| 278 | |
| 279 | When an exception has been assigned using ``as target``, it is cleared at the |
| 280 | end of the except clause. This is as if :: |
| 281 | |
| 282 | except E as N: |
| 283 | foo |
| 284 | |
| 285 | was translated to :: |
| 286 | |
| 287 | except E as N: |
| 288 | try: |
| 289 | foo |
| 290 | finally: |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 291 | del N |
| 292 | |
Benjamin Peterson | fb288da | 2010-06-29 01:27:35 +0000 | [diff] [blame] | 293 | This means the exception must be assigned to a different name to be able to |
| 294 | refer to it after the except clause. Exceptions are cleared because with the |
| 295 | traceback attached to them, they form a reference cycle with the stack frame, |
| 296 | keeping all locals in that frame alive until the next garbage collection occurs. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 297 | |
| 298 | .. index:: |
| 299 | module: sys |
| 300 | object: traceback |
| 301 | |
| 302 | Before an except clause's suite is executed, details about the exception are |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 303 | stored in the :mod:`sys` module and can be accessed via :func:`sys.exc_info`. |
Georg Brandl | b30f330 | 2011-01-06 09:23:56 +0000 | [diff] [blame] | 304 | :func:`sys.exc_info` returns a 3-tuple consisting of the exception class, the |
| 305 | exception instance and a traceback object (see section :ref:`types`) identifying |
Géry Ogam | d515c61 | 2020-12-21 14:13:08 +0100 | [diff] [blame] | 306 | the point in the program where the exception occurred. The details about the |
| 307 | exception accessed via :func:`sys.exc_info` are restored to their previous values |
| 308 | when leaving an exception handler:: |
| 309 | |
| 310 | >>> print(sys.exc_info()) |
| 311 | (None, None, None) |
| 312 | >>> try: |
| 313 | ... raise TypeError |
| 314 | ... except: |
| 315 | ... print(sys.exc_info()) |
| 316 | ... try: |
| 317 | ... raise ValueError |
| 318 | ... except: |
| 319 | ... print(sys.exc_info()) |
| 320 | ... print(sys.exc_info()) |
| 321 | ... |
| 322 | (<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>) |
| 323 | (<class 'ValueError'>, ValueError(), <traceback object at 0x10efad040>) |
| 324 | (<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>) |
| 325 | >>> print(sys.exc_info()) |
| 326 | (None, None, None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 327 | |
| 328 | .. index:: |
| 329 | keyword: else |
| 330 | statement: return |
| 331 | statement: break |
| 332 | statement: continue |
| 333 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 334 | The optional :keyword:`!else` clause is executed if the control flow leaves the |
Andrés Delfino | b086c8a | 2018-11-11 16:33:51 -0300 | [diff] [blame] | 335 | :keyword:`try` suite, no exception was raised, and no :keyword:`return`, |
| 336 | :keyword:`continue`, or :keyword:`break` statement was executed. Exceptions in |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 337 | the :keyword:`!else` clause are not handled by the preceding :keyword:`except` |
Andrés Delfino | b086c8a | 2018-11-11 16:33:51 -0300 | [diff] [blame] | 338 | clauses. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 339 | |
| 340 | .. index:: keyword: finally |
| 341 | |
| 342 | If :keyword:`finally` is present, it specifies a 'cleanup' handler. The |
| 343 | :keyword:`try` clause is executed, including any :keyword:`except` and |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 344 | :keyword:`!else` clauses. If an exception occurs in any of the clauses and is |
| 345 | not handled, the exception is temporarily saved. The :keyword:`!finally` clause |
Mark Dickinson | 05ee581 | 2012-09-24 20:16:38 +0100 | [diff] [blame] | 346 | is executed. If there is a saved exception it is re-raised at the end of the |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 347 | :keyword:`!finally` clause. If the :keyword:`!finally` clause raises another |
Mark Dickinson | 05ee581 | 2012-09-24 20:16:38 +0100 | [diff] [blame] | 348 | exception, the saved exception is set as the context of the new exception. |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 349 | If the :keyword:`!finally` clause executes a :keyword:`return`, :keyword:`break` |
Serhiy Storchaka | fe2bbb1 | 2018-03-18 09:56:52 +0200 | [diff] [blame] | 350 | or :keyword:`continue` statement, the saved exception is discarded:: |
Andrew Svetlov | f158d86 | 2012-08-14 15:38:15 +0300 | [diff] [blame] | 351 | |
Zachary Ware | 9fafc9f | 2014-05-06 09:18:17 -0500 | [diff] [blame] | 352 | >>> def f(): |
| 353 | ... try: |
| 354 | ... 1/0 |
| 355 | ... finally: |
| 356 | ... return 42 |
| 357 | ... |
| 358 | >>> f() |
| 359 | 42 |
Andrew Svetlov | f158d86 | 2012-08-14 15:38:15 +0300 | [diff] [blame] | 360 | |
| 361 | The exception information is not available to the program during execution of |
| 362 | the :keyword:`finally` clause. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 363 | |
| 364 | .. index:: |
| 365 | statement: return |
| 366 | statement: break |
| 367 | statement: continue |
| 368 | |
| 369 | When a :keyword:`return`, :keyword:`break` or :keyword:`continue` statement is |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 370 | executed in the :keyword:`try` suite of a :keyword:`!try`...\ :keyword:`!finally` |
Serhiy Storchaka | fe2bbb1 | 2018-03-18 09:56:52 +0200 | [diff] [blame] | 371 | statement, the :keyword:`finally` clause is also executed 'on the way out.' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 372 | |
Zachary Ware | 8edd532 | 2014-05-06 09:07:13 -0500 | [diff] [blame] | 373 | The return value of a function is determined by the last :keyword:`return` |
| 374 | statement executed. Since the :keyword:`finally` clause always executes, a |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 375 | :keyword:`!return` statement executed in the :keyword:`!finally` clause will |
Zachary Ware | 8edd532 | 2014-05-06 09:07:13 -0500 | [diff] [blame] | 376 | always be the last one executed:: |
| 377 | |
| 378 | >>> def foo(): |
| 379 | ... try: |
| 380 | ... return 'try' |
| 381 | ... finally: |
| 382 | ... return 'finally' |
| 383 | ... |
| 384 | >>> foo() |
| 385 | 'finally' |
| 386 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 387 | Additional information on exceptions can be found in section :ref:`exceptions`, |
| 388 | and information on using the :keyword:`raise` statement to generate exceptions |
| 389 | may be found in section :ref:`raise`. |
| 390 | |
Serhiy Storchaka | fe2bbb1 | 2018-03-18 09:56:52 +0200 | [diff] [blame] | 391 | .. versionchanged:: 3.8 |
| 392 | Prior to Python 3.8, a :keyword:`continue` statement was illegal in the |
| 393 | :keyword:`finally` clause due to a problem with the implementation. |
| 394 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 395 | |
| 396 | .. _with: |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 397 | .. _as: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 398 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 399 | The :keyword:`!with` statement |
| 400 | ============================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 401 | |
Terry Jan Reedy | 7c895ed | 2014-04-29 00:58:56 -0400 | [diff] [blame] | 402 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 403 | ! statement: with |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 404 | keyword: as |
| 405 | single: as; with statement |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 406 | single: , (comma); with statement |
| 407 | single: : (colon); compound statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 408 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 409 | The :keyword:`with` statement is used to wrap the execution of a block with |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 410 | methods defined by a context manager (see section :ref:`context-managers`). |
| 411 | This allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` |
| 412 | usage patterns to be encapsulated for convenient reuse. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 413 | |
Victor Stinner | 8af239e | 2020-09-18 09:10:15 +0200 | [diff] [blame] | 414 | .. productionlist:: python-grammar |
Pablo Galindo | 7c8e0b0 | 2021-01-25 23:15:51 +0000 | [diff] [blame] | 415 | with_stmt: "with" ( "(" `with_stmt_contents` ","? ")" | `with_stmt_contents` ) ":" `suite` |
| 416 | with_stmt_contents: `with_item` ("," `with_item`)* |
Georg Brandl | 0c31562 | 2009-05-25 21:10:36 +0000 | [diff] [blame] | 417 | with_item: `expression` ["as" `target`] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 418 | |
Georg Brandl | 0c31562 | 2009-05-25 21:10:36 +0000 | [diff] [blame] | 419 | The execution of the :keyword:`with` statement with one "item" proceeds as follows: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 420 | |
Georg Brandl | 3387f48 | 2010-09-03 22:40:02 +0000 | [diff] [blame] | 421 | #. The context expression (the expression given in the :token:`with_item`) is |
| 422 | evaluated to obtain a context manager. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 423 | |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 424 | #. The context manager's :meth:`__enter__` is loaded for later use. |
| 425 | |
Benjamin Peterson | 876b2f2 | 2009-06-28 03:18:59 +0000 | [diff] [blame] | 426 | #. The context manager's :meth:`__exit__` is loaded for later use. |
| 427 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 428 | #. The context manager's :meth:`__enter__` method is invoked. |
| 429 | |
| 430 | #. If a target was included in the :keyword:`with` statement, the return value |
| 431 | from :meth:`__enter__` is assigned to it. |
| 432 | |
| 433 | .. note:: |
| 434 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 435 | The :keyword:`with` statement guarantees that if the :meth:`__enter__` |
| 436 | method returns without an error, then :meth:`__exit__` will always be |
Benjamin Peterson | 876b2f2 | 2009-06-28 03:18:59 +0000 | [diff] [blame] | 437 | called. Thus, if an error occurs during the assignment to the target list, |
| 438 | it will be treated the same as an error occurring within the suite would |
| 439 | be. See step 6 below. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 440 | |
| 441 | #. The suite is executed. |
| 442 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 443 | #. The context manager's :meth:`__exit__` method is invoked. If an exception |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 444 | caused the suite to be exited, its type, value, and traceback are passed as |
| 445 | arguments to :meth:`__exit__`. Otherwise, three :const:`None` arguments are |
| 446 | supplied. |
| 447 | |
| 448 | If the suite was exited due to an exception, and the return value from the |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 449 | :meth:`__exit__` method was false, the exception is reraised. If the return |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 450 | value was true, the exception is suppressed, and execution continues with the |
| 451 | statement following the :keyword:`with` statement. |
| 452 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 453 | If the suite was exited for any reason other than an exception, the return |
| 454 | value from :meth:`__exit__` is ignored, and execution proceeds at the normal |
| 455 | location for the kind of exit that was taken. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 456 | |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 457 | The following code:: |
| 458 | |
| 459 | with EXPRESSION as TARGET: |
| 460 | SUITE |
| 461 | |
| 462 | is semantically equivalent to:: |
| 463 | |
| 464 | manager = (EXPRESSION) |
| 465 | enter = type(manager).__enter__ |
| 466 | exit = type(manager).__exit__ |
| 467 | value = enter(manager) |
| 468 | hit_except = False |
| 469 | |
| 470 | try: |
| 471 | TARGET = value |
| 472 | SUITE |
| 473 | except: |
| 474 | hit_except = True |
| 475 | if not exit(manager, *sys.exc_info()): |
| 476 | raise |
| 477 | finally: |
| 478 | if not hit_except: |
| 479 | exit(manager, None, None, None) |
| 480 | |
Georg Brandl | 0c31562 | 2009-05-25 21:10:36 +0000 | [diff] [blame] | 481 | With more than one item, the context managers are processed as if multiple |
| 482 | :keyword:`with` statements were nested:: |
| 483 | |
| 484 | with A() as a, B() as b: |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 485 | SUITE |
Georg Brandl | 0c31562 | 2009-05-25 21:10:36 +0000 | [diff] [blame] | 486 | |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 487 | is semantically equivalent to:: |
Georg Brandl | 0c31562 | 2009-05-25 21:10:36 +0000 | [diff] [blame] | 488 | |
| 489 | with A() as a: |
| 490 | with B() as b: |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 491 | SUITE |
Georg Brandl | 0c31562 | 2009-05-25 21:10:36 +0000 | [diff] [blame] | 492 | |
Pablo Galindo | 7c8e0b0 | 2021-01-25 23:15:51 +0000 | [diff] [blame] | 493 | You can also write multi-item context managers in multiple lines if |
| 494 | the items are surrounded by parentheses. For example:: |
| 495 | |
| 496 | with ( |
| 497 | A() as a, |
| 498 | B() as b, |
| 499 | ): |
| 500 | SUITE |
| 501 | |
Georg Brandl | 0c31562 | 2009-05-25 21:10:36 +0000 | [diff] [blame] | 502 | .. versionchanged:: 3.1 |
| 503 | Support for multiple context expressions. |
| 504 | |
Pablo Galindo | 7c8e0b0 | 2021-01-25 23:15:51 +0000 | [diff] [blame] | 505 | .. versionchanged:: 3.10 |
| 506 | Support for using grouping parentheses to break the statement in multiple lines. |
| 507 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 508 | .. seealso:: |
| 509 | |
Serhiy Storchaka | e4ba872 | 2016-03-31 15:30:54 +0300 | [diff] [blame] | 510 | :pep:`343` - The "with" statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 511 | The specification, background, and examples for the Python :keyword:`with` |
| 512 | statement. |
| 513 | |
Daniel F Moisset | a22bca6 | 2021-03-01 04:08:38 +0000 | [diff] [blame] | 514 | .. _match: |
| 515 | |
| 516 | The :keyword:`!match` statement |
| 517 | =============================== |
| 518 | |
| 519 | .. index:: |
| 520 | ! statement: match |
| 521 | ! keyword: case |
| 522 | ! single: pattern matching |
| 523 | keyword: if |
| 524 | keyword: as |
| 525 | pair: match; case |
| 526 | single: : (colon); compound statement |
| 527 | |
| 528 | .. versionadded:: 3.10 |
| 529 | |
| 530 | The match statement is used for pattern matching. Syntax: |
| 531 | |
| 532 | .. productionlist:: python-grammar |
| 533 | match_stmt: 'match' `subject_expr` ":" NEWLINE INDENT `case_block`+ DEDENT |
| 534 | subject_expr: `star_named_expression` "," `star_named_expressions`? |
| 535 | : | `named_expression` |
Ken Jin | 37a5e22 | 2021-04-13 01:03:20 +0800 | [diff] [blame] | 536 | case_block: 'case' `patterns` [`guard`] ":" `block` |
Daniel F Moisset | a22bca6 | 2021-03-01 04:08:38 +0000 | [diff] [blame] | 537 | |
| 538 | .. note:: |
| 539 | This section uses single quotes to denote |
| 540 | :ref:`soft keywords <soft-keywords>`. |
| 541 | |
| 542 | Pattern matching takes a pattern as input (following ``case``) and a subject |
| 543 | value (following ``match``). The pattern (which may contain subpatterns) is |
| 544 | matched against the subject value. The outcomes are: |
| 545 | |
| 546 | * A match success or failure (also termed a pattern success or failure). |
| 547 | |
| 548 | * Possible binding of matched values to a name. The prerequisites for this are |
| 549 | further discussed below. |
| 550 | |
| 551 | The ``match`` and ``case`` keywords are :ref:`soft keywords <soft-keywords>`. |
| 552 | |
| 553 | .. seealso:: |
| 554 | |
| 555 | * :pep:`634` -- Structural Pattern Matching: Specification |
| 556 | * :pep:`636` -- Structural Pattern Matching: Tutorial |
| 557 | |
| 558 | |
| 559 | Overview |
| 560 | -------- |
| 561 | |
| 562 | Here's an overview of the logical flow of a match statement: |
| 563 | |
| 564 | |
| 565 | #. The subject expression ``subject_expr`` is evaluated and a resulting subject |
| 566 | value obtained. If the subject expression contains a comma, a tuple is |
| 567 | constructed using :ref:`the standard rules <typesseq-tuple>`. |
| 568 | |
| 569 | #. Each pattern in a ``case_block`` is attempted to match with the subject value. The |
| 570 | specific rules for success or failure are described below. The match attempt can also |
| 571 | bind some or all of the standalone names within the pattern. The precise |
| 572 | pattern binding rules vary per pattern type and are |
| 573 | specified below. **Name bindings made during a successful pattern match |
| 574 | outlive the executed block and can be used after the match statement**. |
| 575 | |
| 576 | .. note:: |
| 577 | |
| 578 | During failed pattern matches, some subpatterns may succeed. Do not |
| 579 | rely on bindings being made for a failed match. Conversely, do not |
| 580 | rely on variables remaining unchanged after a failed match. The exact |
| 581 | behavior is dependent on implementation and may vary. This is an |
| 582 | intentional decision made to allow different implementations to add |
| 583 | optimizations. |
| 584 | |
| 585 | #. If the pattern succeeds, the corresponding guard (if present) is evaluated. In |
| 586 | this case all name bindings are guaranteed to have happened. |
| 587 | |
| 588 | * If the guard evaluates as truthy or missing, the ``block`` inside ``case_block`` is |
| 589 | executed. |
| 590 | |
| 591 | * Otherwise, the next ``case_block`` is attempted as described above. |
| 592 | |
| 593 | * If there are no further case blocks, the match statement is completed. |
| 594 | |
| 595 | .. note:: |
| 596 | |
| 597 | Users should generally never rely on a pattern being evaluated. Depending on |
| 598 | implementation, the interpreter may cache values or use other optimizations |
| 599 | which skip repeated evaluations. |
| 600 | |
| 601 | A sample match statement:: |
| 602 | |
| 603 | >>> flag = False |
| 604 | >>> match (100, 200): |
| 605 | ... case (100, 300): # Mismatch: 200 != 300 |
| 606 | ... print('Case 1') |
| 607 | ... case (100, 200) if flag: # Successful match, but guard fails |
| 608 | ... print('Case 2') |
| 609 | ... case (100, y): # Matches and binds y to 200 |
| 610 | ... print(f'Case 3, y: {y}') |
| 611 | ... case _: # Pattern not attempted |
| 612 | ... print('Case 4, I match anything!') |
| 613 | ... |
| 614 | Case 3, y: 200 |
| 615 | |
| 616 | |
| 617 | In this case, ``if flag`` is a guard. Read more about that in the next section. |
| 618 | |
| 619 | Guards |
| 620 | ------ |
| 621 | |
| 622 | .. index:: ! guard |
| 623 | |
| 624 | .. productionlist:: python-grammar |
| 625 | guard: "if" `named_expression` |
| 626 | |
| 627 | A ``guard`` (which is part of the ``case``) must succeed for code inside |
| 628 | the ``case`` block to execute. It takes the form: :keyword:`if` followed by an |
| 629 | expression. |
| 630 | |
| 631 | |
| 632 | The logical flow of a ``case`` block with a ``guard`` follows: |
| 633 | |
| 634 | #. Check that the pattern in the ``case`` block succeeded. If the pattern |
| 635 | failed, the ``guard`` is not evaluated and the next ``case`` block is |
| 636 | checked. |
| 637 | |
| 638 | #. If the pattern succeeded, evaluate the ``guard``. |
| 639 | |
| 640 | * If the ``guard`` condition evaluates to "truthy", the case block is |
| 641 | selected. |
| 642 | |
| 643 | * If the ``guard`` condition evaluates to "falsy", the case block is not |
| 644 | selected. |
| 645 | |
| 646 | * If the ``guard`` raises an exception during evaluation, the exception |
| 647 | bubbles up. |
| 648 | |
| 649 | Guards are allowed to have side effects as they are expressions. Guard |
| 650 | evaluation must proceed from the first to the last case block, one at a time, |
| 651 | skipping case blocks whose pattern(s) don't all succeed. (I.e., |
| 652 | guard evaluation must happen in order.) Guard evaluation must stop once a case |
| 653 | block is selected. |
| 654 | |
| 655 | |
| 656 | .. _irrefutable_case: |
| 657 | |
| 658 | Irrefutable Case Blocks |
| 659 | ----------------------- |
| 660 | |
| 661 | .. index:: irrefutable case block, case block |
| 662 | |
| 663 | An irrefutable case block is a match-all case block. A match statement may have |
| 664 | at most one irrefutable case block, and it must be last. |
| 665 | |
| 666 | A case block is considered irrefutable if it has no guard and its pattern is |
| 667 | irrefutable. A pattern is considered irrefutable if we can prove from its |
| 668 | syntax alone that it will always succeed. Only the following patterns are |
| 669 | irrefutable: |
| 670 | |
| 671 | * :ref:`as-patterns` whose left-hand side is irrefutable |
| 672 | |
| 673 | * :ref:`or-patterns` containing at least one irrefutable pattern |
| 674 | |
| 675 | * :ref:`capture-patterns` |
| 676 | |
| 677 | * :ref:`wildcard-patterns` |
| 678 | |
| 679 | * parenthesized irrefutable patterns |
| 680 | |
| 681 | |
| 682 | Patterns |
| 683 | -------- |
| 684 | |
| 685 | .. index:: |
| 686 | single: ! patterns |
| 687 | single: AS pattern, OR pattern, capture pattern, wildcard pattern |
| 688 | |
| 689 | .. note:: |
| 690 | This section uses grammar notations beyond standard EBNF: |
| 691 | |
| 692 | * the notation ``SEP.RULE+`` is shorthand for ``RULE (SEP RULE)*`` |
| 693 | |
| 694 | * the notation ``!RULE`` is shorthand for a negative lookahead assertion |
| 695 | |
| 696 | |
| 697 | The top-level syntax for ``patterns`` is: |
| 698 | |
| 699 | .. productionlist:: python-grammar |
| 700 | patterns: `open_sequence_pattern` | `pattern` |
| 701 | pattern: `as_pattern` | `or_pattern` |
| 702 | closed_pattern: | `literal_pattern` |
| 703 | : | `capture_pattern` |
| 704 | : | `wildcard_pattern` |
| 705 | : | `value_pattern` |
| 706 | : | `group_pattern` |
| 707 | : | `sequence_pattern` |
| 708 | : | `mapping_pattern` |
| 709 | : | `class_pattern` |
| 710 | |
| 711 | The descriptions below will include a description "in simple terms" of what a pattern |
| 712 | does for illustration purposes (credits to Raymond Hettinger for a document that |
| 713 | inspired most of the descriptions). Note that these descriptions are purely for |
| 714 | illustration purposes and **may not** reflect |
| 715 | the underlying implementation. Furthermore, they do not cover all valid forms. |
| 716 | |
| 717 | |
| 718 | .. _or-patterns: |
| 719 | |
| 720 | OR Patterns |
| 721 | ^^^^^^^^^^^ |
| 722 | |
| 723 | An OR pattern is two or more patterns separated by vertical |
| 724 | bars ``|``. Syntax: |
| 725 | |
| 726 | .. productionlist:: python-grammar |
| 727 | or_pattern: "|".`closed_pattern`+ |
| 728 | |
| 729 | Only the final subpattern may be :ref:`irrefutable <irrefutable_case>`, and each |
| 730 | subpattern must bind the same set of names to avoid ambiguity. |
| 731 | |
| 732 | An OR pattern matches each of its subpatterns in turn to the subject value, |
| 733 | until one succeeds. The OR pattern is then considered successful. Otherwise, |
| 734 | if none of the subpatterns succeed, the OR pattern fails. |
| 735 | |
| 736 | In simple terms, ``P1 | P2 | ...`` will try to match ``P1``, if it fails it will try to |
| 737 | match ``P2``, succeeding immediately if any succeeds, failing otherwise. |
| 738 | |
| 739 | .. _as-patterns: |
| 740 | |
| 741 | AS Patterns |
| 742 | ^^^^^^^^^^^ |
| 743 | |
| 744 | An AS pattern matches an OR pattern on the left of the :keyword:`as` |
| 745 | keyword against a subject. Syntax: |
| 746 | |
| 747 | .. productionlist:: python-grammar |
| 748 | as_pattern: `or_pattern` "as" `capture_pattern` |
| 749 | |
| 750 | If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds |
| 751 | the subject to the name on the right of the as keyword and succeeds. |
| 752 | ``capture_pattern`` cannot be a a ``_``. |
| 753 | |
| 754 | In simple terms ``P as NAME`` will match with ``P``, and on success it will |
| 755 | set ``NAME = <subject>``. |
| 756 | |
| 757 | |
| 758 | .. _literal-patterns: |
| 759 | |
| 760 | Literal Patterns |
| 761 | ^^^^^^^^^^^^^^^^ |
| 762 | |
| 763 | A literal pattern corresponds to most |
| 764 | :ref:`literals <literals>` in Python. Syntax: |
| 765 | |
| 766 | .. productionlist:: python-grammar |
| 767 | literal_pattern: `signed_number` |
| 768 | : | `signed_number` "+" NUMBER |
| 769 | : | `signed_number` "-" NUMBER |
| 770 | : | `strings` |
| 771 | : | "None" |
| 772 | : | "True" |
| 773 | : | "False" |
| 774 | : | `signed_number`: NUMBER | "-" NUMBER |
| 775 | |
| 776 | The rule ``strings`` and the token ``NUMBER`` are defined in the |
| 777 | :doc:`standard Python grammar <./grammar>`. Triple-quoted strings are |
| 778 | supported. Raw strings and byte strings are supported. :ref:`f-strings` are |
| 779 | not supported. |
| 780 | |
| 781 | The forms ``signed_number '+' NUMBER`` and ``signed_number '-' NUMBER`` are |
| 782 | for expressing :ref:`complex numbers <imaginary>`; they require a real number |
| 783 | on the left and an imaginary number on the right. E.g. ``3 + 4j``. |
| 784 | |
| 785 | In simple terms, ``LITERAL`` will succeed only if ``<subject> == LITERAL``. For |
| 786 | the singletons ``None``, ``True`` and ``False``, the :keyword:`is` operator is used. |
| 787 | |
| 788 | .. _capture-patterns: |
| 789 | |
| 790 | Capture Patterns |
| 791 | ^^^^^^^^^^^^^^^^ |
| 792 | |
| 793 | A capture pattern binds the subject value to a name. |
| 794 | Syntax: |
| 795 | |
| 796 | .. productionlist:: python-grammar |
| 797 | capture_pattern: !'_' NAME |
| 798 | |
| 799 | A single underscore ``_`` is not a capture pattern (this is what ``!'_'`` |
| 800 | expresses). And is instead treated as a :token:`wildcard_pattern`. |
| 801 | |
| 802 | In a given pattern, a given name can only be bound once. E.g. |
| 803 | ``case x, x: ...`` is invalid while ``case [x] | x: ...`` is allowed. |
| 804 | |
| 805 | Capture patterns always succeed. The binding follows scoping rules |
| 806 | established by the assignment expression operator in :pep:`572`; the |
| 807 | name becomes a local variable in the closest containing function scope unless |
| 808 | there's an applicable :keyword:`global` or :keyword:`nonlocal` statement. |
| 809 | |
| 810 | In simple terms ``NAME`` will always succeed and it will set ``NAME = <subject>``. |
| 811 | |
| 812 | .. _wildcard-patterns: |
| 813 | |
| 814 | Wildcard Patterns |
| 815 | ^^^^^^^^^^^^^^^^^ |
| 816 | |
| 817 | A wildcard pattern always succeeds (matches anything) |
| 818 | and binds no name. Syntax: |
| 819 | |
| 820 | .. productionlist:: python-grammar |
| 821 | wildcard_pattern: '_' |
| 822 | |
| 823 | ``_`` is a :ref:`soft keyword <soft-keywords>`. |
| 824 | |
| 825 | In simple terms, ``_`` will always succeed. |
| 826 | |
| 827 | .. _value-patterns: |
| 828 | |
| 829 | Value Patterns |
| 830 | ^^^^^^^^^^^^^^ |
| 831 | |
| 832 | A value pattern represents a named value in Python. |
| 833 | Syntax: |
| 834 | |
| 835 | .. productionlist:: python-grammar |
| 836 | value_pattern: `attr` |
| 837 | attr: `name_or_attr` "." NAME |
| 838 | name_or_attr: `attr` | NAME |
| 839 | |
| 840 | The dotted name in the pattern is looked up using standard Python |
| 841 | :ref:`name resolution rules <resolve_names>`. The pattern succeeds if the |
| 842 | value found compares equal to the subject value (using the ``==`` equality |
| 843 | operator). |
| 844 | |
| 845 | In simple terms ``NAME1.NAME2`` will succeed only if ``<subject> == NAME1.NAME2`` |
| 846 | |
| 847 | .. note:: |
| 848 | |
| 849 | If the same value occurs multiple times in the same match statement, the |
| 850 | interpreter may cache the first value found and reuse it rather than repeat |
| 851 | the same lookup. This cache is strictly tied to a given execution of a |
| 852 | given match statement. |
| 853 | |
| 854 | .. _group-patterns: |
| 855 | |
| 856 | Group Patterns |
| 857 | ^^^^^^^^^^^^^^ |
| 858 | |
| 859 | A group pattern allows users to add parentheses around patterns to |
| 860 | emphasize the intended grouping. Otherwise, it has no additional syntax. |
| 861 | Syntax: |
| 862 | |
| 863 | .. productionlist:: python-grammar |
Ken Jin | 37a5e22 | 2021-04-13 01:03:20 +0800 | [diff] [blame] | 864 | group_pattern: "(" `pattern` ")" |
Daniel F Moisset | a22bca6 | 2021-03-01 04:08:38 +0000 | [diff] [blame] | 865 | |
| 866 | In simple terms ``(P)`` has the same effect as ``P``. |
| 867 | |
| 868 | .. _sequence-patterns: |
| 869 | |
| 870 | Sequence Patterns |
| 871 | ^^^^^^^^^^^^^^^^^ |
| 872 | |
| 873 | A sequence pattern contains several subpatterns to be matched against sequence elements. |
| 874 | The syntax is similar to the unpacking of a list or tuple. |
| 875 | |
| 876 | .. productionlist:: python-grammar |
| 877 | sequence_pattern: "[" [`maybe_sequence_pattern`] "]" |
| 878 | : | "(" [`open_sequence_pattern`] ")" |
| 879 | open_sequence_pattern: `maybe_star_pattern` "," [`maybe_sequence_pattern`] |
| 880 | maybe_sequence_pattern: ",".`maybe_star_pattern`+ ","? |
| 881 | maybe_star_pattern: `star_pattern` | `pattern` |
| 882 | star_pattern: "*" (`capture_pattern` | `wildcard_pattern`) |
| 883 | |
| 884 | There is no difference if parentheses or square brackets |
| 885 | are used for sequence patterns (i.e. ``(...)`` vs ``[...]`` ). |
| 886 | |
| 887 | .. note:: |
| 888 | A single pattern enclosed in parentheses without a trailing comma |
| 889 | (e.g. ``(3 | 4)``) is a :ref:`group pattern <group-patterns>`. |
| 890 | While a single pattern enclosed in square brackets (e.g. ``[3 | 4]``) is |
| 891 | still a sequence pattern. |
| 892 | |
| 893 | At most one star subpattern may be in a sequence pattern. The star subpattern |
| 894 | may occur in any position. If no star subpattern is present, the sequence |
| 895 | pattern is a fixed-length sequence pattern; otherwise it is a variable-length |
| 896 | sequence pattern. |
| 897 | |
| 898 | The following is the logical flow for matching a sequence pattern against a |
| 899 | subject value: |
| 900 | |
| 901 | #. If the subject value is not an instance of a |
| 902 | :class:`collections.abc.Sequence` the sequence pattern fails. |
| 903 | |
| 904 | #. If the subject value is an instance of ``str``, ``bytes`` or ``bytearray`` |
| 905 | the sequence pattern fails. |
| 906 | |
| 907 | #. The subsequent steps depend on whether the sequence pattern is fixed or |
| 908 | variable-length. |
| 909 | |
| 910 | If the sequence pattern is fixed-length: |
| 911 | |
| 912 | #. If the length of the subject sequence is not equal to the number of |
| 913 | subpatterns, the sequence pattern fails |
| 914 | |
| 915 | #. Subpatterns in the sequence pattern are matched to their corresponding |
| 916 | items in the subject sequence from left to right. Matching stops as soon |
| 917 | as a subpattern fails. If all subpatterns succeed in matching their |
| 918 | corresponding item, the sequence pattern succeeds. |
| 919 | |
| 920 | Otherwise, if the sequence pattern is variable-length: |
| 921 | |
| 922 | #. If the length of the subject sequence is less than the number of non-star |
| 923 | subpatterns, the sequence pattern fails. |
| 924 | |
| 925 | #. The leading non-star subpatterns are matched to their corresponding items |
| 926 | as for fixed-length sequences. |
| 927 | |
| 928 | #. If the previous step succeeds, the star subpattern matches a list formed |
| 929 | of the remaining subject items, excluding the remaining items |
| 930 | corresponding to non-star subpatterns following the star subpattern. |
| 931 | |
| 932 | #. Remaining non-star subpatterns are matched to their corresponding subject |
| 933 | items, as for a fixed-length sequence. |
| 934 | |
| 935 | .. note:: The length of the subject sequence is obtained via |
| 936 | :func:`len` (i.e. via the :meth:`__len__` protocol). This length may be |
| 937 | cached by the interpreter in a similar manner as |
| 938 | :ref:`value patterns <value-patterns>`. |
| 939 | |
| 940 | |
| 941 | In simple terms ``[P1, P2, P3,`` ... ``, P<N>]`` matches only if all the following |
| 942 | happens: |
| 943 | |
| 944 | * ``isinstance(<subject>, collections.abc.Sequence)`` |
| 945 | * ``len(subject) == <N>`` |
| 946 | * ``P1`` matches ``<subject>[0]`` (note that this match can also bind names) |
| 947 | * ``P2`` matches ``<subject>[1]`` (note that this match can also bind names) |
| 948 | * ... and so on for the corresponding pattern/element. |
| 949 | |
| 950 | .. _mapping-patterns: |
| 951 | |
| 952 | Mapping Patterns |
| 953 | ^^^^^^^^^^^^^^^^ |
| 954 | |
| 955 | A mapping pattern contains one or more key-value patterns. The syntax is |
| 956 | similar to the construction of a dictionary. |
| 957 | Syntax: |
| 958 | |
| 959 | .. productionlist:: python-grammar |
| 960 | mapping_pattern: "{" [`items_pattern`] "}" |
| 961 | items_pattern: ",".`key_value_pattern`+ ","? |
| 962 | key_value_pattern: (`literal_pattern` | `value_pattern`) ":" `pattern` |
| 963 | : | `double_star_pattern` |
| 964 | double_star_pattern: "**" `capture_pattern` |
| 965 | |
| 966 | At most one double star pattern may be in a mapping pattern. The double star |
| 967 | pattern must be the last subpattern in the mapping pattern. |
| 968 | |
| 969 | Duplicate key values in mapping patterns are disallowed. (If all key patterns |
| 970 | are literal patterns this is considered a syntax error; otherwise this is a |
| 971 | runtime error and will raise :exc:`ValueError`.) |
| 972 | |
| 973 | The following is the logical flow for matching a mapping pattern against a |
| 974 | subject value: |
| 975 | |
| 976 | #. If the subject value is not an instance of :class:`collections.abc.Mapping`, |
| 977 | the mapping pattern fails. |
| 978 | |
| 979 | #. If every key given in the mapping pattern is present in the subject mapping, |
| 980 | and the pattern for each key matches the corresponding item of the subject |
| 981 | mapping, the mapping pattern succeeds. |
| 982 | |
| 983 | #. If duplicate keys are detected in the mapping pattern, the pattern is |
| 984 | considered invalid and :exc:`ValueError` is raised. |
| 985 | |
| 986 | .. note:: Key-value pairs are matched using the two-argument form of the mapping |
| 987 | subject's ``get()`` method. Matched key-value pairs must already be present |
| 988 | in the mapping, and not created on-the-fly via :meth:`__missing__` or |
| 989 | :meth:`__getitem__`. |
| 990 | |
| 991 | In simple terms ``{KEY1: P1, KEY2: P2, ... }`` matches only if all the following |
| 992 | happens: |
| 993 | |
| 994 | * ``isinstance(<subject>, collections.abc.Mapping)`` |
| 995 | * ``KEY1 in <subject>`` |
| 996 | * ``P1`` matches ``<subject>[KEY1]`` |
| 997 | * ... and so on for the corresponding KEY/pattern pair. |
| 998 | |
| 999 | |
| 1000 | .. _class-patterns: |
| 1001 | |
| 1002 | Class Patterns |
| 1003 | ^^^^^^^^^^^^^^ |
| 1004 | |
| 1005 | A class pattern represents a class and its positional and keyword arguments |
| 1006 | (if any). Syntax: |
| 1007 | |
| 1008 | .. productionlist:: python-grammar |
| 1009 | class_pattern: `name_or_attr` "(" [`pattern_arguments` ","?] ")" |
| 1010 | pattern_arguments: `positional_patterns` ["," `keyword_patterns`] |
| 1011 | : | `keyword_patterns` |
| 1012 | positional_patterns: ",".`pattern`+ |
| 1013 | keyword_patterns: ",".`keyword_pattern`+ |
| 1014 | keyword_pattern: NAME "=" `pattern` |
| 1015 | |
| 1016 | The same keyword should not be repeated in class patterns. |
| 1017 | |
| 1018 | The following is the logical flow for matching a mapping pattern against a |
| 1019 | subject value: |
| 1020 | |
| 1021 | #. If ``name_or_attr`` is not an instance of the builtin :class:`type` , raise |
| 1022 | :exc:`TypeError`. |
| 1023 | |
| 1024 | #. If the subject value is not an instance of ``name_or_attr`` (tested via |
| 1025 | :func:`isinstance`), the class pattern fails. |
| 1026 | |
| 1027 | #. If no pattern arguments are present, the pattern succeeds. Otherwise, |
| 1028 | the subsequent steps depend on whether keyword or positional argument patterns |
| 1029 | are present. |
| 1030 | |
| 1031 | For a number of built-in types (specified below), a single positional |
| 1032 | subpattern is accepted which will match the entire subject; for these types |
Ken Jin | 5143fd1 | 2021-04-07 00:03:00 +0800 | [diff] [blame] | 1033 | keyword patterns also work as for other types. |
Daniel F Moisset | a22bca6 | 2021-03-01 04:08:38 +0000 | [diff] [blame] | 1034 | |
| 1035 | If only keyword patterns are present, they are processed as follows, |
| 1036 | one by one: |
| 1037 | |
| 1038 | I. The keyword is looked up as an attribute on the subject. |
| 1039 | |
| 1040 | * If this raises an exception other than :exc:`AttributeError`, the |
| 1041 | exception bubbles up. |
| 1042 | |
| 1043 | * If this raises :exc:`AttributeError`, the class pattern has failed. |
| 1044 | |
| 1045 | * Else, the subpattern associated with the keyword pattern is matched |
| 1046 | against the subject's attribute value. If this fails, the class |
| 1047 | pattern fails; if this succeeds, the match proceeds to the next keyword. |
| 1048 | |
| 1049 | |
| 1050 | II. If all keyword patterns succeed, the class pattern succeeds. |
| 1051 | |
| 1052 | If any positional patterns are present, they are converted to keyword |
| 1053 | patterns using the :data:`~object.__match_args__` attribute on the class |
| 1054 | ``name_or_attr`` before matching: |
| 1055 | |
| 1056 | I. The equivalent of ``getattr(cls, "__match_args__", ()))`` is called. |
| 1057 | |
| 1058 | * If this raises an exception, the exception bubbles up. |
| 1059 | |
Ken Jin | 5143fd1 | 2021-04-07 00:03:00 +0800 | [diff] [blame] | 1060 | * If the returned value is not a tuple, the conversion fails and |
Daniel F Moisset | a22bca6 | 2021-03-01 04:08:38 +0000 | [diff] [blame] | 1061 | :exc:`TypeError` is raised. |
| 1062 | |
| 1063 | * If there are more positional patterns than ``len(cls.__match_args__)``, |
| 1064 | :exc:`TypeError` is raised. |
| 1065 | |
| 1066 | * Otherwise, positional pattern ``i`` is converted to a keyword pattern |
| 1067 | using ``__match_args__[i]`` as the keyword. ``__match_args__[i]`` must |
| 1068 | be a string; if not :exc:`TypeError` is raised. |
| 1069 | |
| 1070 | * If there are duplicate keywords, :exc:`TypeError` is raised. |
| 1071 | |
| 1072 | .. seealso:: :ref:`class-pattern-matching` |
| 1073 | |
| 1074 | II. Once all positional patterns have been converted to keyword patterns, |
| 1075 | the match proceeds as if there were only keyword patterns. |
| 1076 | |
| 1077 | For the following built-in types the handling of positional subpatterns is |
| 1078 | different: |
| 1079 | |
| 1080 | * :class:`bool` |
| 1081 | * :class:`bytearray` |
| 1082 | * :class:`bytes` |
| 1083 | * :class:`dict` |
| 1084 | * :class:`float` |
| 1085 | * :class:`frozenset` |
| 1086 | * :class:`int` |
| 1087 | * :class:`list` |
| 1088 | * :class:`set` |
| 1089 | * :class:`str` |
| 1090 | * :class:`tuple` |
| 1091 | |
| 1092 | These classes accept a single positional argument, and the pattern there is matched |
| 1093 | against the whole object rather than an attribute. For example ``int(0|1)`` matches |
| 1094 | the value ``0``, but not the values ``0.0`` or ``False``. |
| 1095 | |
| 1096 | In simple terms ``CLS(P1, attr=P2)`` matches only if the following happens: |
| 1097 | |
| 1098 | * ``isinstance(<subject>, CLS)`` |
| 1099 | * convert ``P1`` to a keyword pattern using ``CLS.__match_args__`` |
| 1100 | * For each keyword argument ``attr=P2``: |
| 1101 | * ``hasattr(<subject>, "attr")`` |
| 1102 | * ``P2`` matches ``<subject>.attr`` |
| 1103 | * ... and so on for the corresponding keyword argument/pattern pair. |
| 1104 | |
| 1105 | .. seealso:: |
| 1106 | |
| 1107 | * :pep:`634` -- Structural Pattern Matching: Specification |
| 1108 | * :pep:`636` -- Structural Pattern Matching: Tutorial |
| 1109 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1110 | |
Chris Jerdonek | b430994 | 2012-12-25 14:54:44 -0800 | [diff] [blame] | 1111 | .. index:: |
| 1112 | single: parameter; function definition |
| 1113 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1114 | .. _function: |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 1115 | .. _def: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1116 | |
| 1117 | Function definitions |
| 1118 | ==================== |
| 1119 | |
| 1120 | .. index:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1121 | statement: def |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1122 | pair: function; definition |
| 1123 | pair: function; name |
| 1124 | pair: name; binding |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1125 | object: user-defined function |
| 1126 | object: function |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1127 | pair: function; name |
| 1128 | pair: name; binding |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1129 | single: () (parentheses); function definition |
| 1130 | single: , (comma); parameter list |
| 1131 | single: : (colon); compound statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1132 | |
| 1133 | A function definition defines a user-defined function object (see section |
| 1134 | :ref:`types`): |
| 1135 | |
Victor Stinner | 8af239e | 2020-09-18 09:10:15 +0200 | [diff] [blame] | 1136 | .. productionlist:: python-grammar |
Andrés Delfino | caccca78 | 2018-07-07 17:24:46 -0300 | [diff] [blame] | 1137 | funcdef: [`decorators`] "def" `funcname` "(" [`parameter_list`] ")" |
| 1138 | : ["->" `expression`] ":" `suite` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1139 | decorators: `decorator`+ |
Brandt Bucher | 8f13053 | 2020-03-07 10:23:49 -0800 | [diff] [blame] | 1140 | decorator: "@" `assignment_expression` NEWLINE |
Pablo Galindo | 29cb21d | 2019-05-29 22:59:00 +0100 | [diff] [blame] | 1141 | parameter_list: `defparameter` ("," `defparameter`)* "," "/" ["," [`parameter_list_no_posonly`]] |
Pablo Galindo | b76302d | 2019-05-29 00:45:32 +0100 | [diff] [blame] | 1142 | : | `parameter_list_no_posonly` |
| 1143 | parameter_list_no_posonly: `defparameter` ("," `defparameter`)* ["," [`parameter_list_starargs`]] |
| 1144 | : | `parameter_list_starargs` |
Robert Collins | df39599 | 2015-08-12 08:00:06 +1200 | [diff] [blame] | 1145 | parameter_list_starargs: "*" [`parameter`] ("," `defparameter`)* ["," ["**" `parameter` [","]]] |
Andrés Delfino | caccca78 | 2018-07-07 17:24:46 -0300 | [diff] [blame] | 1146 | : | "**" `parameter` [","] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1147 | parameter: `identifier` [":" `expression`] |
| 1148 | defparameter: `parameter` ["=" `expression`] |
| 1149 | funcname: `identifier` |
| 1150 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1151 | |
| 1152 | A function definition is an executable statement. Its execution binds the |
| 1153 | function name in the current local namespace to a function object (a wrapper |
| 1154 | around the executable code for the function). This function object contains a |
| 1155 | reference to the current global namespace as the global namespace to be used |
| 1156 | when the function is called. |
| 1157 | |
| 1158 | The function definition does not execute the function body; this gets executed |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 1159 | only when the function is called. [#]_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1160 | |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 1161 | .. index:: |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1162 | single: @ (at); function definition |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 1163 | |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 1164 | A function definition may be wrapped by one or more :term:`decorator` expressions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1165 | Decorator expressions are evaluated when the function is defined, in the scope |
| 1166 | that contains the function definition. The result must be a callable, which is |
| 1167 | invoked with the function object as the only argument. The returned value is |
| 1168 | bound to the function name instead of the function object. Multiple decorators |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1169 | are applied in nested fashion. For example, the following code :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1170 | |
| 1171 | @f1(arg) |
| 1172 | @f2 |
| 1173 | def func(): pass |
| 1174 | |
Berker Peksag | 6cafece | 2016-08-03 10:17:21 +0300 | [diff] [blame] | 1175 | is roughly equivalent to :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1176 | |
| 1177 | def func(): pass |
| 1178 | func = f1(arg)(f2(func)) |
| 1179 | |
Berker Peksag | 6cafece | 2016-08-03 10:17:21 +0300 | [diff] [blame] | 1180 | except that the original function is not temporarily bound to the name ``func``. |
| 1181 | |
Brandt Bucher | 8f13053 | 2020-03-07 10:23:49 -0800 | [diff] [blame] | 1182 | .. versionchanged:: 3.9 |
| 1183 | Functions may be decorated with any valid :token:`assignment_expression`. |
| 1184 | Previously, the grammar was much more restrictive; see :pep:`614` for |
| 1185 | details. |
| 1186 | |
Chris Jerdonek | b430994 | 2012-12-25 14:54:44 -0800 | [diff] [blame] | 1187 | .. index:: |
| 1188 | triple: default; parameter; value |
| 1189 | single: argument; function definition |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1190 | single: = (equals); function definition |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1191 | |
Chris Jerdonek | b430994 | 2012-12-25 14:54:44 -0800 | [diff] [blame] | 1192 | When one or more :term:`parameters <parameter>` have the form *parameter* ``=`` |
| 1193 | *expression*, the function is said to have "default parameter values." For a |
| 1194 | parameter with a default value, the corresponding :term:`argument` may be |
| 1195 | omitted from a call, in which |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1196 | case the parameter's default value is substituted. If a parameter has a default |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1197 | value, all following parameters up until the "``*``" must also have a default |
| 1198 | value --- this is a syntactic restriction that is not expressed by the grammar. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1199 | |
Benjamin Peterson | 1ef876c | 2013-02-10 09:29:59 -0500 | [diff] [blame] | 1200 | **Default parameter values are evaluated from left to right when the function |
| 1201 | definition is executed.** This means that the expression is evaluated once, when |
| 1202 | the function is defined, and that the same "pre-computed" value is used for each |
Andre Delfino | b9f6ac9 | 2020-07-22 20:58:19 -0300 | [diff] [blame] | 1203 | call. This is especially important to understand when a default parameter value is a |
Benjamin Peterson | 1ef876c | 2013-02-10 09:29:59 -0500 | [diff] [blame] | 1204 | mutable object, such as a list or a dictionary: if the function modifies the |
Andre Delfino | b9f6ac9 | 2020-07-22 20:58:19 -0300 | [diff] [blame] | 1205 | object (e.g. by appending an item to a list), the default parameter value is in effect |
Benjamin Peterson | 1ef876c | 2013-02-10 09:29:59 -0500 | [diff] [blame] | 1206 | modified. This is generally not what was intended. A way around this is to use |
| 1207 | ``None`` as the default, and explicitly test for it in the body of the function, |
| 1208 | e.g.:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1209 | |
| 1210 | def whats_on_the_telly(penguin=None): |
| 1211 | if penguin is None: |
| 1212 | penguin = [] |
| 1213 | penguin.append("property of the zoo") |
| 1214 | return penguin |
| 1215 | |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 1216 | .. index:: |
Saiyang Gou | 58d72ca | 2021-04-07 12:06:43 -0700 | [diff] [blame] | 1217 | single: / (slash); function definition |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1218 | single: * (asterisk); function definition |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1219 | single: **; function definition |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 1220 | |
| 1221 | Function call semantics are described in more detail in section :ref:`calls`. A |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1222 | function call always assigns values to all parameters mentioned in the parameter |
Saiyang Gou | 58d72ca | 2021-04-07 12:06:43 -0700 | [diff] [blame] | 1223 | list, either from positional arguments, from keyword arguments, or from default |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1224 | values. If the form "``*identifier``" is present, it is initialized to a tuple |
Eric Snow | b957b0c | 2016-09-08 13:59:58 -0700 | [diff] [blame] | 1225 | receiving any excess positional parameters, defaulting to the empty tuple. |
| 1226 | If the form "``**identifier``" is present, it is initialized to a new |
| 1227 | ordered mapping receiving any excess keyword arguments, defaulting to a |
| 1228 | new empty mapping of the same type. Parameters after "``*``" or |
| 1229 | "``*identifier``" are keyword-only parameters and may only be passed |
Saiyang Gou | 58d72ca | 2021-04-07 12:06:43 -0700 | [diff] [blame] | 1230 | by keyword arguments. Parameters before "``/``" are positional-only parameters |
| 1231 | and may only be passed by positional arguments. |
| 1232 | |
| 1233 | .. versionchanged:: 3.8 |
| 1234 | The ``/`` function parameter syntax may be used to indicate positional-only |
| 1235 | parameters. See :pep:`570` for details. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1236 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1237 | .. index:: |
| 1238 | pair: function; annotations |
| 1239 | single: ->; function annotations |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1240 | single: : (colon); function annotations |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1241 | |
Cheryl Sabella | b7105c9 | 2018-12-24 00:09:09 -0500 | [diff] [blame] | 1242 | Parameters may have an :term:`annotation <function annotation>` of the form "``: expression``" |
| 1243 | following the parameter name. Any parameter may have an annotation, even those of the form |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1244 | ``*identifier`` or ``**identifier``. Functions may have "return" annotation of |
| 1245 | the form "``-> expression``" after the parameter list. These annotations can be |
Guido van Rossum | 95e4d58 | 2018-01-26 08:20:18 -0800 | [diff] [blame] | 1246 | any valid Python expression. The presence of annotations does not change the |
Batuhan Taskaya | 044a104 | 2020-10-06 23:03:02 +0300 | [diff] [blame] | 1247 | semantics of a function. The annotation values are available as string values |
| 1248 | in a dictionary keyed by the parameters' names in the :attr:`__annotations__` |
| 1249 | attribute of the function object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1250 | |
Georg Brandl | 242e6a0 | 2013-10-06 10:28:39 +0200 | [diff] [blame] | 1251 | .. index:: pair: lambda; expression |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1252 | |
| 1253 | It is also possible to create anonymous functions (functions not bound to a |
Georg Brandl | 242e6a0 | 2013-10-06 10:28:39 +0200 | [diff] [blame] | 1254 | name), for immediate use in expressions. This uses lambda expressions, described in |
| 1255 | section :ref:`lambda`. Note that the lambda expression is merely a shorthand for a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1256 | simplified function definition; a function defined in a ":keyword:`def`" |
| 1257 | statement can be passed around or assigned to another name just like a function |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 1258 | defined by a lambda expression. The ":keyword:`!def`" form is actually more powerful |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1259 | since it allows the execution of multiple statements and annotations. |
| 1260 | |
Georg Brandl | 242e6a0 | 2013-10-06 10:28:39 +0200 | [diff] [blame] | 1261 | **Programmer's note:** Functions are first-class objects. A "``def``" statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1262 | executed inside a function definition defines a local function that can be |
| 1263 | returned or passed around. Free variables used in the nested function can |
| 1264 | access the local variables of the function containing the def. See section |
| 1265 | :ref:`naming` for details. |
| 1266 | |
Georg Brandl | 64a4094 | 2012-03-10 09:22:47 +0100 | [diff] [blame] | 1267 | .. seealso:: |
| 1268 | |
| 1269 | :pep:`3107` - Function Annotations |
| 1270 | The original specification for function annotations. |
| 1271 | |
Guido van Rossum | 95e4d58 | 2018-01-26 08:20:18 -0800 | [diff] [blame] | 1272 | :pep:`484` - Type Hints |
| 1273 | Definition of a standard meaning for annotations: type hints. |
| 1274 | |
| 1275 | :pep:`526` - Syntax for Variable Annotations |
| 1276 | Ability to type hint variable declarations, including class |
| 1277 | variables and instance variables |
| 1278 | |
| 1279 | :pep:`563` - Postponed Evaluation of Annotations |
| 1280 | Support for forward references within annotations by preserving |
| 1281 | annotations in a string form at runtime instead of eager evaluation. |
| 1282 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1283 | |
| 1284 | .. _class: |
| 1285 | |
| 1286 | Class definitions |
| 1287 | ================= |
| 1288 | |
| 1289 | .. index:: |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1290 | object: class |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1291 | statement: class |
| 1292 | pair: class; definition |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1293 | pair: class; name |
| 1294 | pair: name; binding |
| 1295 | pair: execution; frame |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1296 | single: inheritance |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 1297 | single: docstring |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1298 | single: () (parentheses); class definition |
| 1299 | single: , (comma); expression list |
| 1300 | single: : (colon); compound statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1301 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1302 | A class definition defines a class object (see section :ref:`types`): |
| 1303 | |
Victor Stinner | 8af239e | 2020-09-18 09:10:15 +0200 | [diff] [blame] | 1304 | .. productionlist:: python-grammar |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1305 | classdef: [`decorators`] "class" `classname` [`inheritance`] ":" `suite` |
Benjamin Peterson | 54044d6 | 2016-05-16 23:20:22 -0700 | [diff] [blame] | 1306 | inheritance: "(" [`argument_list`] ")" |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1307 | classname: `identifier` |
| 1308 | |
Georg Brandl | 65e5f80 | 2010-08-02 18:10:13 +0000 | [diff] [blame] | 1309 | A class definition is an executable statement. The inheritance list usually |
| 1310 | gives a list of base classes (see :ref:`metaclasses` for more advanced uses), so |
| 1311 | each item in the list should evaluate to a class object which allows |
Éric Araujo | 28053fb | 2010-11-22 03:09:19 +0000 | [diff] [blame] | 1312 | subclassing. Classes without an inheritance list inherit, by default, from the |
| 1313 | base class :class:`object`; hence, :: |
| 1314 | |
| 1315 | class Foo: |
| 1316 | pass |
| 1317 | |
| 1318 | is equivalent to :: |
| 1319 | |
| 1320 | class Foo(object): |
| 1321 | pass |
Georg Brandl | 65e5f80 | 2010-08-02 18:10:13 +0000 | [diff] [blame] | 1322 | |
| 1323 | The class's suite is then executed in a new execution frame (see :ref:`naming`), |
| 1324 | using a newly created local namespace and the original global namespace. |
| 1325 | (Usually, the suite contains mostly function definitions.) When the class's |
| 1326 | suite finishes execution, its execution frame is discarded but its local |
| 1327 | namespace is saved. [#]_ A class object is then created using the inheritance |
| 1328 | list for the base classes and the saved local namespace for the attribute |
| 1329 | dictionary. The class name is bound to this class object in the original local |
| 1330 | namespace. |
| 1331 | |
Eric Snow | 92a6c17 | 2016-09-05 14:50:11 -0700 | [diff] [blame] | 1332 | The order in which attributes are defined in the class body is preserved |
Eric Snow | 4f29e75 | 2016-09-08 15:11:11 -0700 | [diff] [blame] | 1333 | in the new class's ``__dict__``. Note that this is reliable only right |
| 1334 | after the class is created and only for classes that were defined using |
| 1335 | the definition syntax. |
Eric Snow | 92a6c17 | 2016-09-05 14:50:11 -0700 | [diff] [blame] | 1336 | |
Georg Brandl | 65e5f80 | 2010-08-02 18:10:13 +0000 | [diff] [blame] | 1337 | Class creation can be customized heavily using :ref:`metaclasses <metaclasses>`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1338 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1339 | .. index:: |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1340 | single: @ (at); class definition |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1341 | |
Georg Brandl | f414272 | 2010-10-17 10:38:20 +0000 | [diff] [blame] | 1342 | Classes can also be decorated: just like when decorating functions, :: |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1343 | |
| 1344 | @f1(arg) |
| 1345 | @f2 |
| 1346 | class Foo: pass |
| 1347 | |
Berker Peksag | 6cafece | 2016-08-03 10:17:21 +0300 | [diff] [blame] | 1348 | is roughly equivalent to :: |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1349 | |
| 1350 | class Foo: pass |
| 1351 | Foo = f1(arg)(f2(Foo)) |
| 1352 | |
Georg Brandl | f414272 | 2010-10-17 10:38:20 +0000 | [diff] [blame] | 1353 | The evaluation rules for the decorator expressions are the same as for function |
Berker Peksag | 6cafece | 2016-08-03 10:17:21 +0300 | [diff] [blame] | 1354 | decorators. The result is then bound to the class name. |
Georg Brandl | f414272 | 2010-10-17 10:38:20 +0000 | [diff] [blame] | 1355 | |
Brandt Bucher | 8f13053 | 2020-03-07 10:23:49 -0800 | [diff] [blame] | 1356 | .. versionchanged:: 3.9 |
| 1357 | Classes may be decorated with any valid :token:`assignment_expression`. |
| 1358 | Previously, the grammar was much more restrictive; see :pep:`614` for |
| 1359 | details. |
| 1360 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1361 | **Programmer's note:** Variables defined in the class definition are class |
Georg Brandl | 65e5f80 | 2010-08-02 18:10:13 +0000 | [diff] [blame] | 1362 | attributes; they are shared by instances. Instance attributes can be set in a |
| 1363 | method with ``self.name = value``. Both class and instance attributes are |
| 1364 | accessible through the notation "``self.name``", and an instance attribute hides |
| 1365 | a class attribute with the same name when accessed in this way. Class |
| 1366 | attributes can be used as defaults for instance attributes, but using mutable |
| 1367 | values there can lead to unexpected results. :ref:`Descriptors <descriptors>` |
| 1368 | can be used to create instance variables with different implementation details. |
Georg Brandl | 85eb8c1 | 2007-08-31 16:33:38 +0000 | [diff] [blame] | 1369 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1370 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1371 | .. seealso:: |
| 1372 | |
Andrés Delfino | 0f14fc1 | 2018-10-19 20:31:15 -0300 | [diff] [blame] | 1373 | :pep:`3115` - Metaclasses in Python 3000 |
| 1374 | The proposal that changed the declaration of metaclasses to the current |
| 1375 | syntax, and the semantics for how classes with metaclasses are |
| 1376 | constructed. |
| 1377 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1378 | :pep:`3129` - Class Decorators |
Andrés Delfino | 0f14fc1 | 2018-10-19 20:31:15 -0300 | [diff] [blame] | 1379 | The proposal that added class decorators. Function and method decorators |
| 1380 | were introduced in :pep:`318`. |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1381 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 1382 | |
Elvis Pranskevichus | 63536bd | 2018-05-19 23:15:06 -0400 | [diff] [blame] | 1383 | .. _async: |
| 1384 | |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1385 | Coroutines |
| 1386 | ========== |
| 1387 | |
Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 1388 | .. versionadded:: 3.5 |
| 1389 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 1390 | .. index:: statement: async def |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1391 | .. _`async def`: |
| 1392 | |
| 1393 | Coroutine function definition |
| 1394 | ----------------------------- |
| 1395 | |
Victor Stinner | 8af239e | 2020-09-18 09:10:15 +0200 | [diff] [blame] | 1396 | .. productionlist:: python-grammar |
Andrés Delfino | caccca78 | 2018-07-07 17:24:46 -0300 | [diff] [blame] | 1397 | async_funcdef: [`decorators`] "async" "def" `funcname` "(" [`parameter_list`] ")" |
| 1398 | : ["->" `expression`] ":" `suite` |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1399 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 1400 | .. index:: |
| 1401 | keyword: async |
| 1402 | keyword: await |
| 1403 | |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1404 | Execution of Python coroutines can be suspended and resumed at many points |
Andre Delfino | 8adf8d1 | 2020-10-12 10:52:30 -0300 | [diff] [blame] | 1405 | (see :term:`coroutine`). :keyword:`await` expressions, :keyword:`async for` and |
| 1406 | :keyword:`async with` can only be used in the body of a coroutine function. |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1407 | |
| 1408 | Functions defined with ``async def`` syntax are always coroutine functions, |
| 1409 | even if they do not contain ``await`` or ``async`` keywords. |
| 1410 | |
Andrés Delfino | 95f68b1 | 2018-10-28 07:41:57 -0300 | [diff] [blame] | 1411 | It is a :exc:`SyntaxError` to use a ``yield from`` expression inside the body |
| 1412 | of a coroutine function. |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1413 | |
Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 1414 | An example of a coroutine function:: |
| 1415 | |
| 1416 | async def func(param1, param2): |
| 1417 | do_stuff() |
| 1418 | await some_coroutine() |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1419 | |
Andre Delfino | 8adf8d1 | 2020-10-12 10:52:30 -0300 | [diff] [blame] | 1420 | .. versionchanged:: 3.7 |
| 1421 | ``await`` and ``async`` are now keywords; previously they were only |
| 1422 | treated as such inside the body of a coroutine function. |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1423 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 1424 | .. index:: statement: async for |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1425 | .. _`async for`: |
| 1426 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 1427 | The :keyword:`!async for` statement |
| 1428 | ----------------------------------- |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1429 | |
Victor Stinner | 8af239e | 2020-09-18 09:10:15 +0200 | [diff] [blame] | 1430 | .. productionlist:: python-grammar |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1431 | async_for_stmt: "async" `for_stmt` |
| 1432 | |
Nick Gaya | 4b8cdfc | 2020-12-11 00:27:35 -0800 | [diff] [blame] | 1433 | An :term:`asynchronous iterable` provides an ``__aiter__`` method that directly |
| 1434 | returns an :term:`asynchronous iterator`, which can call asynchronous code in |
| 1435 | its ``__anext__`` method. |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1436 | |
| 1437 | The ``async for`` statement allows convenient iteration over asynchronous |
Nick Gaya | 4b8cdfc | 2020-12-11 00:27:35 -0800 | [diff] [blame] | 1438 | iterables. |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1439 | |
| 1440 | The following code:: |
| 1441 | |
| 1442 | async for TARGET in ITER: |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1443 | SUITE |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1444 | else: |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1445 | SUITE2 |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1446 | |
| 1447 | Is semantically equivalent to:: |
| 1448 | |
| 1449 | iter = (ITER) |
Yury Selivanov | a6f6edb | 2016-06-09 15:08:31 -0400 | [diff] [blame] | 1450 | iter = type(iter).__aiter__(iter) |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1451 | running = True |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1452 | |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1453 | while running: |
| 1454 | try: |
| 1455 | TARGET = await type(iter).__anext__(iter) |
| 1456 | except StopAsyncIteration: |
| 1457 | running = False |
| 1458 | else: |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1459 | SUITE |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1460 | else: |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1461 | SUITE2 |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1462 | |
| 1463 | See also :meth:`__aiter__` and :meth:`__anext__` for details. |
| 1464 | |
Andrés Delfino | 95f68b1 | 2018-10-28 07:41:57 -0300 | [diff] [blame] | 1465 | It is a :exc:`SyntaxError` to use an ``async for`` statement outside the |
| 1466 | body of a coroutine function. |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1467 | |
| 1468 | |
Yury Selivanov | 66f8828 | 2015-06-24 11:04:15 -0400 | [diff] [blame] | 1469 | .. index:: statement: async with |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1470 | .. _`async with`: |
| 1471 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 1472 | The :keyword:`!async with` statement |
| 1473 | ------------------------------------ |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1474 | |
Victor Stinner | 8af239e | 2020-09-18 09:10:15 +0200 | [diff] [blame] | 1475 | .. productionlist:: python-grammar |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1476 | async_with_stmt: "async" `with_stmt` |
| 1477 | |
| 1478 | An :term:`asynchronous context manager` is a :term:`context manager` that is |
| 1479 | able to suspend execution in its *enter* and *exit* methods. |
| 1480 | |
| 1481 | The following code:: |
| 1482 | |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1483 | async with EXPRESSION as TARGET: |
| 1484 | SUITE |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1485 | |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1486 | is semantically equivalent to:: |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1487 | |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1488 | manager = (EXPRESSION) |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1489 | aenter = type(manager).__aenter__ |
Géry Ogam | 1d1b97a | 2020-01-14 12:58:29 +0100 | [diff] [blame] | 1490 | aexit = type(manager).__aexit__ |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1491 | value = await aenter(manager) |
| 1492 | hit_except = False |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1493 | |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1494 | try: |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1495 | TARGET = value |
| 1496 | SUITE |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1497 | except: |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1498 | hit_except = True |
| 1499 | if not await aexit(manager, *sys.exc_info()): |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1500 | raise |
Géry Ogam | 226e6e7 | 2019-12-30 05:24:51 +0000 | [diff] [blame] | 1501 | finally: |
| 1502 | if not hit_except: |
| 1503 | await aexit(manager, None, None, None) |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1504 | |
| 1505 | See also :meth:`__aenter__` and :meth:`__aexit__` for details. |
| 1506 | |
Andrés Delfino | 95f68b1 | 2018-10-28 07:41:57 -0300 | [diff] [blame] | 1507 | It is a :exc:`SyntaxError` to use an ``async with`` statement outside the |
| 1508 | body of a coroutine function. |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1509 | |
| 1510 | .. seealso:: |
| 1511 | |
| 1512 | :pep:`492` - Coroutines with async and await syntax |
Andrés Delfino | 0f14fc1 | 2018-10-19 20:31:15 -0300 | [diff] [blame] | 1513 | The proposal that made coroutines a proper standalone concept in Python, |
| 1514 | and added supporting syntax. |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 1515 | |
| 1516 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1517 | .. rubric:: Footnotes |
| 1518 | |
Ezio Melotti | fc3db8a | 2011-06-26 11:25:28 +0300 | [diff] [blame] | 1519 | .. [#] The exception is propagated to the invocation stack unless |
| 1520 | there is a :keyword:`finally` clause which happens to raise another |
| 1521 | exception. That new exception causes the old one to be lost. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1522 | |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 1523 | .. [#] A string literal appearing as the first statement in the function body is |
| 1524 | transformed into the function's ``__doc__`` attribute and therefore the |
| 1525 | function's :term:`docstring`. |
| 1526 | |
| 1527 | .. [#] A string literal appearing as the first statement in the class body is |
| 1528 | transformed into the namespace's ``__doc__`` item and therefore the class's |
| 1529 | :term:`docstring`. |