Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 2 | .. _simple: |
| 3 | |
| 4 | ***************** |
| 5 | Simple statements |
| 6 | ***************** |
| 7 | |
| 8 | .. index:: pair: simple; statement |
| 9 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 10 | A simple statement is comprised within a single logical line. Several simple |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 11 | statements may occur on a single line separated by semicolons. The syntax for |
| 12 | simple statements is: |
| 13 | |
| 14 | .. productionlist:: |
| 15 | simple_stmt: `expression_stmt` |
| 16 | : | `assert_stmt` |
| 17 | : | `assignment_stmt` |
| 18 | : | `augmented_assignment_stmt` |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 19 | : | `annotated_assignment_stmt` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 20 | : | `pass_stmt` |
| 21 | : | `del_stmt` |
| 22 | : | `return_stmt` |
| 23 | : | `yield_stmt` |
| 24 | : | `raise_stmt` |
| 25 | : | `break_stmt` |
| 26 | : | `continue_stmt` |
| 27 | : | `import_stmt` |
Andrés Delfino | cdb96f4 | 2018-11-07 14:32:18 -0300 | [diff] [blame] | 28 | : | `future_stmt` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 29 | : | `global_stmt` |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 30 | : | `nonlocal_stmt` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 31 | |
| 32 | |
| 33 | .. _exprstmts: |
| 34 | |
| 35 | Expression statements |
| 36 | ===================== |
| 37 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 38 | .. index:: |
| 39 | pair: expression; statement |
| 40 | pair: expression; list |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 41 | .. index:: pair: expression; list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 42 | |
| 43 | Expression statements are used (mostly interactively) to compute and write a |
| 44 | value, or (usually) to call a procedure (a function that returns no meaningful |
| 45 | result; in Python, procedures return the value ``None``). Other uses of |
| 46 | expression statements are allowed and occasionally useful. The syntax for an |
| 47 | expression statement is: |
| 48 | |
| 49 | .. productionlist:: |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 50 | expression_stmt: `starred_expression` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 51 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 52 | An expression statement evaluates the expression list (which may be a single |
| 53 | expression). |
| 54 | |
| 55 | .. index:: |
| 56 | builtin: repr |
| 57 | object: None |
| 58 | pair: string; conversion |
| 59 | single: output |
| 60 | pair: standard; output |
| 61 | pair: writing; values |
| 62 | pair: procedure; call |
| 63 | |
| 64 | In interactive mode, if the value is not ``None``, it is converted to a string |
| 65 | using the built-in :func:`repr` function and the resulting string is written to |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 66 | standard output on a line by itself (except if the result is ``None``, so that |
| 67 | procedure calls do not cause any output.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 68 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 69 | .. _assignment: |
| 70 | |
| 71 | Assignment statements |
| 72 | ===================== |
| 73 | |
| 74 | .. index:: |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 75 | single: = (equals); assignment statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 76 | pair: assignment; statement |
| 77 | pair: binding; name |
| 78 | pair: rebinding; name |
| 79 | object: mutable |
| 80 | pair: attribute; assignment |
| 81 | |
| 82 | Assignment statements are used to (re)bind names to values and to modify |
| 83 | attributes or items of mutable objects: |
| 84 | |
| 85 | .. productionlist:: |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 86 | assignment_stmt: (`target_list` "=")+ (`starred_expression` | `yield_expression`) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 87 | target_list: `target` ("," `target`)* [","] |
| 88 | target: `identifier` |
Berker Peksag | 094c9c9 | 2016-05-18 08:44:29 +0300 | [diff] [blame] | 89 | : | "(" [`target_list`] ")" |
| 90 | : | "[" [`target_list`] "]" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 91 | : | `attributeref` |
| 92 | : | `subscription` |
| 93 | : | `slicing` |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 94 | : | "*" `target` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 95 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 96 | (See section :ref:`primaries` for the syntax definitions for *attributeref*, |
| 97 | *subscription*, and *slicing*.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 98 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 99 | An assignment statement evaluates the expression list (remember that this can be |
| 100 | a single expression or a comma-separated list, the latter yielding a tuple) and |
| 101 | assigns the single resulting object to each of the target lists, from left to |
| 102 | right. |
| 103 | |
| 104 | .. index:: |
| 105 | single: target |
| 106 | pair: target; list |
| 107 | |
| 108 | Assignment is defined recursively depending on the form of the target (list). |
| 109 | When a target is part of a mutable object (an attribute reference, subscription |
| 110 | or slicing), the mutable object must ultimately perform the assignment and |
| 111 | decide about its validity, and may raise an exception if the assignment is |
| 112 | unacceptable. The rules observed by various types and the exceptions raised are |
| 113 | given with the definition of the object types (see section :ref:`types`). |
| 114 | |
| 115 | .. index:: triple: target; list; assignment |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 116 | single: , (comma); in target list |
| 117 | single: * (asterisk); in assignment target list |
| 118 | single: [] (square brackets); in assignment target list |
| 119 | single: () (parentheses); in assignment target list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 120 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 121 | Assignment of an object to a target list, optionally enclosed in parentheses or |
| 122 | square brackets, is recursively defined as follows. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 123 | |
Julien Palard | 082875d | 2018-11-12 00:59:39 +0100 | [diff] [blame] | 124 | * If the target list is a single target with no trailing comma, |
| 125 | optionally in parentheses, the object is assigned to that target. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 126 | |
Julien Palard | 082875d | 2018-11-12 00:59:39 +0100 | [diff] [blame] | 127 | * Else: The object must be an iterable with the same number of |
Berker Peksag | 094c9c9 | 2016-05-18 08:44:29 +0300 | [diff] [blame] | 128 | items as there are targets in the target list, and the items are assigned, |
| 129 | from left to right, to the corresponding targets. |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 130 | |
| 131 | * If the target list contains one target prefixed with an asterisk, called a |
Berker Peksag | 094c9c9 | 2016-05-18 08:44:29 +0300 | [diff] [blame] | 132 | "starred" target: The object must be an iterable with at least as many items |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 133 | as there are targets in the target list, minus one. The first items of the |
Berker Peksag | 094c9c9 | 2016-05-18 08:44:29 +0300 | [diff] [blame] | 134 | iterable are assigned, from left to right, to the targets before the starred |
| 135 | target. The final items of the iterable are assigned to the targets after |
| 136 | the starred target. A list of the remaining items in the iterable is then |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 137 | assigned to the starred target (the list can be empty). |
| 138 | |
Berker Peksag | 094c9c9 | 2016-05-18 08:44:29 +0300 | [diff] [blame] | 139 | * Else: The object must be an iterable with the same number of items as there |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 140 | are targets in the target list, and the items are assigned, from left to |
| 141 | right, to the corresponding targets. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 142 | |
| 143 | Assignment of an object to a single target is recursively defined as follows. |
| 144 | |
| 145 | * If the target is an identifier (name): |
| 146 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 147 | * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal` |
| 148 | statement in the current code block: the name is bound to the object in the |
| 149 | current local namespace. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 150 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 151 | * Otherwise: the name is bound to the object in the global namespace or the |
| 152 | outer namespace determined by :keyword:`nonlocal`, respectively. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 153 | |
Georg Brandl | 482b151 | 2010-03-21 09:02:59 +0000 | [diff] [blame] | 154 | .. index:: single: destructor |
| 155 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 156 | The name is rebound if it was already bound. This may cause the reference |
| 157 | count for the object previously bound to the name to reach zero, causing the |
| 158 | object to be deallocated and its destructor (if it has one) to be called. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 159 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 160 | .. index:: pair: attribute; assignment |
| 161 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 162 | * If the target is an attribute reference: The primary expression in the |
| 163 | reference is evaluated. It should yield an object with assignable attributes; |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 164 | if this is not the case, :exc:`TypeError` is raised. That object is then |
| 165 | asked to assign the assigned object to the given attribute; if it cannot |
| 166 | perform the assignment, it raises an exception (usually but not necessarily |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 167 | :exc:`AttributeError`). |
| 168 | |
Georg Brandl | ee8783d | 2009-09-16 16:00:31 +0000 | [diff] [blame] | 169 | .. _attr-target-note: |
| 170 | |
| 171 | Note: If the object is a class instance and the attribute reference occurs on |
| 172 | both sides of the assignment operator, the RHS expression, ``a.x`` can access |
| 173 | either an instance attribute or (if no instance attribute exists) a class |
| 174 | attribute. The LHS target ``a.x`` is always set as an instance attribute, |
| 175 | creating it if necessary. Thus, the two occurrences of ``a.x`` do not |
| 176 | necessarily refer to the same attribute: if the RHS expression refers to a |
| 177 | class attribute, the LHS creates a new instance attribute as the target of the |
| 178 | assignment:: |
| 179 | |
| 180 | class Cls: |
| 181 | x = 3 # class variable |
| 182 | inst = Cls() |
| 183 | inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3 |
| 184 | |
| 185 | This description does not necessarily apply to descriptor attributes, such as |
| 186 | properties created with :func:`property`. |
| 187 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 188 | .. index:: |
| 189 | pair: subscription; assignment |
| 190 | object: mutable |
| 191 | |
| 192 | * If the target is a subscription: The primary expression in the reference is |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 193 | evaluated. It should yield either a mutable sequence object (such as a list) |
| 194 | or a mapping object (such as a dictionary). Next, the subscript expression is |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 195 | evaluated. |
| 196 | |
| 197 | .. index:: |
| 198 | object: sequence |
| 199 | object: list |
| 200 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 201 | If the primary is a mutable sequence object (such as a list), the subscript |
| 202 | must yield an integer. If it is negative, the sequence's length is added to |
| 203 | it. The resulting value must be a nonnegative integer less than the |
| 204 | sequence's length, and the sequence is asked to assign the assigned object to |
| 205 | its item with that index. If the index is out of range, :exc:`IndexError` is |
| 206 | raised (assignment to a subscripted sequence cannot add new items to a list). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 207 | |
| 208 | .. index:: |
| 209 | object: mapping |
| 210 | object: dictionary |
| 211 | |
| 212 | If the primary is a mapping object (such as a dictionary), the subscript must |
| 213 | have a type compatible with the mapping's key type, and the mapping is then |
| 214 | asked to create a key/datum pair which maps the subscript to the assigned |
| 215 | object. This can either replace an existing key/value pair with the same key |
| 216 | value, or insert a new key/value pair (if no key with the same value existed). |
| 217 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 218 | For user-defined objects, the :meth:`__setitem__` method is called with |
| 219 | appropriate arguments. |
| 220 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 221 | .. index:: pair: slicing; assignment |
| 222 | |
| 223 | * If the target is a slicing: The primary expression in the reference is |
| 224 | evaluated. It should yield a mutable sequence object (such as a list). The |
| 225 | assigned object should be a sequence object of the same type. Next, the lower |
| 226 | and upper bound expressions are evaluated, insofar they are present; defaults |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 227 | are zero and the sequence's length. The bounds should evaluate to integers. |
| 228 | If either bound is negative, the sequence's length is added to it. The |
| 229 | resulting bounds are clipped to lie between zero and the sequence's length, |
| 230 | inclusive. Finally, the sequence object is asked to replace the slice with |
| 231 | the items of the assigned sequence. The length of the slice may be different |
| 232 | from the length of the assigned sequence, thus changing the length of the |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 233 | target sequence, if the target sequence allows it. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 234 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 235 | .. impl-detail:: |
| 236 | |
| 237 | In the current implementation, the syntax for targets is taken to be the same |
| 238 | as for expressions, and invalid syntax is rejected during the code generation |
| 239 | phase, causing less detailed error messages. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 240 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 241 | Although the definition of assignment implies that overlaps between the |
Martin Panter | f0564164 | 2016-05-08 13:48:10 +0000 | [diff] [blame] | 242 | left-hand side and the right-hand side are 'simultaneous' (for example ``a, b = |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 243 | b, a`` swaps two variables), overlaps *within* the collection of assigned-to |
| 244 | variables occur left-to-right, sometimes resulting in confusion. For instance, |
| 245 | the following program prints ``[0, 2]``:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 246 | |
| 247 | x = [0, 1] |
| 248 | i = 0 |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 249 | i, x[i] = 1, 2 # i is updated, then x[i] is updated |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 250 | print(x) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 251 | |
| 252 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 253 | .. seealso:: |
| 254 | |
| 255 | :pep:`3132` - Extended Iterable Unpacking |
| 256 | The specification for the ``*target`` feature. |
| 257 | |
| 258 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 259 | .. _augassign: |
| 260 | |
| 261 | Augmented assignment statements |
| 262 | ------------------------------- |
| 263 | |
| 264 | .. index:: |
| 265 | pair: augmented; assignment |
| 266 | single: statement; assignment, augmented |
Terry Jan Reedy | 9cc9026 | 2014-04-29 01:19:17 -0400 | [diff] [blame] | 267 | single: +=; augmented assignment |
| 268 | single: -=; augmented assignment |
| 269 | single: *=; augmented assignment |
| 270 | single: /=; augmented assignment |
| 271 | single: %=; augmented assignment |
| 272 | single: &=; augmented assignment |
| 273 | single: ^=; augmented assignment |
| 274 | single: |=; augmented assignment |
| 275 | single: **=; augmented assignment |
| 276 | single: //=; augmented assignment |
| 277 | single: >>=; augmented assignment |
| 278 | single: <<=; augmented assignment |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 279 | |
| 280 | Augmented assignment is the combination, in a single statement, of a binary |
| 281 | operation and an assignment statement: |
| 282 | |
| 283 | .. productionlist:: |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 284 | augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`) |
| 285 | augtarget: `identifier` | `attributeref` | `subscription` | `slicing` |
Benjamin Peterson | d51374e | 2014-04-09 23:55:56 -0400 | [diff] [blame] | 286 | augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**=" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 287 | : | ">>=" | "<<=" | "&=" | "^=" | "|=" |
| 288 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 289 | (See section :ref:`primaries` for the syntax definitions of the last three |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 290 | symbols.) |
| 291 | |
| 292 | An augmented assignment evaluates the target (which, unlike normal assignment |
| 293 | statements, cannot be an unpacking) and the expression list, performs the binary |
| 294 | operation specific to the type of assignment on the two operands, and assigns |
| 295 | the result to the original target. The target is only evaluated once. |
| 296 | |
| 297 | An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x + |
| 298 | 1`` to achieve a similar, but not exactly equal effect. In the augmented |
| 299 | version, ``x`` is only evaluated once. Also, when possible, the actual operation |
| 300 | is performed *in-place*, meaning that rather than creating a new object and |
| 301 | assigning that to the target, the old object is modified instead. |
| 302 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 303 | Unlike normal assignments, augmented assignments evaluate the left-hand side |
| 304 | *before* evaluating the right-hand side. For example, ``a[i] += f(x)`` first |
| 305 | looks-up ``a[i]``, then it evaluates ``f(x)`` and performs the addition, and |
| 306 | lastly, it writes the result back to ``a[i]``. |
| 307 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 308 | With the exception of assigning to tuples and multiple targets in a single |
| 309 | statement, the assignment done by augmented assignment statements is handled the |
| 310 | same way as normal assignments. Similarly, with the exception of the possible |
| 311 | *in-place* behavior, the binary operation performed by augmented assignment is |
| 312 | the same as the normal binary operations. |
| 313 | |
Georg Brandl | ee8783d | 2009-09-16 16:00:31 +0000 | [diff] [blame] | 314 | For targets which are attribute references, the same :ref:`caveat about class |
| 315 | and instance attributes <attr-target-note>` applies as for regular assignments. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 316 | |
| 317 | |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 318 | .. _annassign: |
| 319 | |
| 320 | Annotated assignment statements |
| 321 | ------------------------------- |
| 322 | |
| 323 | .. index:: |
| 324 | pair: annotated; assignment |
| 325 | single: statement; assignment, annotated |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 326 | single: : (colon); annotated variable |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 327 | |
Cheryl Sabella | b7105c9 | 2018-12-24 00:09:09 -0500 | [diff] [blame] | 328 | :term:`Annotation <variable annotation>` assignment is the combination, in a single |
| 329 | statement, of a variable or attribute annotation and an optional assignment statement: |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 330 | |
| 331 | .. productionlist:: |
| 332 | annotated_assignment_stmt: `augtarget` ":" `expression` ["=" `expression`] |
| 333 | |
| 334 | The difference from normal :ref:`assignment` is that only single target and |
| 335 | only single right hand side value is allowed. |
| 336 | |
| 337 | For simple names as assignment targets, if in class or module scope, |
| 338 | the annotations are evaluated and stored in a special class or module |
| 339 | attribute :attr:`__annotations__` |
Guido van Rossum | 015d874 | 2016-09-11 09:45:24 -0700 | [diff] [blame] | 340 | that is a dictionary mapping from variable names (mangled if private) to |
| 341 | evaluated annotations. This attribute is writable and is automatically |
| 342 | created at the start of class or module body execution, if annotations |
| 343 | are found statically. |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 344 | |
| 345 | For expressions as assignment targets, the annotations are evaluated if |
| 346 | in class or module scope, but not stored. |
| 347 | |
| 348 | If a name is annotated in a function scope, then this name is local for |
| 349 | that scope. Annotations are never evaluated and stored in function scopes. |
| 350 | |
| 351 | If the right hand side is present, an annotated |
| 352 | assignment performs the actual assignment before evaluating annotations |
| 353 | (where applicable). If the right hand side is not present for an expression |
| 354 | target, then the interpreter evaluates the target except for the last |
| 355 | :meth:`__setitem__` or :meth:`__setattr__` call. |
| 356 | |
| 357 | .. seealso:: |
| 358 | |
Andrés Delfino | 0f14fc1 | 2018-10-19 20:31:15 -0300 | [diff] [blame] | 359 | :pep:`526` - Syntax for Variable Annotations |
| 360 | The proposal that added syntax for annotating the types of variables |
| 361 | (including class variables and instance variables), instead of expressing |
| 362 | them through comments. |
| 363 | |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 364 | :pep:`484` - Type hints |
Andrés Delfino | 0f14fc1 | 2018-10-19 20:31:15 -0300 | [diff] [blame] | 365 | The proposal that added the :mod:`typing` module to provide a standard |
| 366 | syntax for type annotations that can be used in static analysis tools and |
| 367 | IDEs. |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 368 | |
| 369 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 370 | .. _assert: |
| 371 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 372 | The :keyword:`!assert` statement |
| 373 | ================================ |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 374 | |
| 375 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 376 | ! statement: assert |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 377 | pair: debugging; assertions |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 378 | single: , (comma); expression list |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 379 | |
| 380 | Assert statements are a convenient way to insert debugging assertions into a |
| 381 | program: |
| 382 | |
| 383 | .. productionlist:: |
| 384 | assert_stmt: "assert" `expression` ["," `expression`] |
| 385 | |
| 386 | The simple form, ``assert expression``, is equivalent to :: |
| 387 | |
| 388 | if __debug__: |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 389 | if not expression: raise AssertionError |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 390 | |
| 391 | The extended form, ``assert expression1, expression2``, is equivalent to :: |
| 392 | |
| 393 | if __debug__: |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 394 | if not expression1: raise AssertionError(expression2) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 395 | |
| 396 | .. index:: |
| 397 | single: __debug__ |
| 398 | exception: AssertionError |
| 399 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 400 | These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 401 | the built-in variables with those names. In the current implementation, the |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 402 | built-in variable :const:`__debug__` is ``True`` under normal circumstances, |
Andrés Delfino | ea6a28c | 2018-11-07 14:06:45 -0300 | [diff] [blame] | 403 | ``False`` when optimization is requested (command line option :option:`-O`). The current |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 404 | code generator emits no code for an assert statement when optimization is |
| 405 | requested at compile time. Note that it is unnecessary to include the source |
| 406 | code for the expression that failed in the error message; it will be displayed |
| 407 | as part of the stack trace. |
| 408 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 409 | Assignments to :const:`__debug__` are illegal. The value for the built-in variable |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 410 | is determined when the interpreter starts. |
| 411 | |
| 412 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 413 | .. _pass: |
| 414 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 415 | The :keyword:`!pass` statement |
| 416 | ============================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 417 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 418 | .. index:: |
| 419 | statement: pass |
| 420 | pair: null; operation |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 421 | pair: null; operation |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 422 | |
| 423 | .. productionlist:: |
| 424 | pass_stmt: "pass" |
| 425 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 426 | :keyword:`pass` is a null operation --- when it is executed, nothing happens. |
| 427 | It is useful as a placeholder when a statement is required syntactically, but no |
| 428 | code needs to be executed, for example:: |
| 429 | |
| 430 | def f(arg): pass # a function that does nothing (yet) |
| 431 | |
| 432 | class C: pass # a class with no methods (yet) |
| 433 | |
| 434 | |
| 435 | .. _del: |
| 436 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 437 | The :keyword:`!del` statement |
| 438 | ============================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 439 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 440 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 441 | ! statement: del |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 442 | pair: deletion; target |
| 443 | triple: deletion; target; list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 444 | |
| 445 | .. productionlist:: |
| 446 | del_stmt: "del" `target_list` |
| 447 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 448 | Deletion is recursively defined very similar to the way assignment is defined. |
Sandro Tosi | 75c71cc | 2011-12-24 19:56:04 +0100 | [diff] [blame] | 449 | Rather than spelling it out in full details, here are some hints. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 450 | |
| 451 | Deletion of a target list recursively deletes each target, from left to right. |
| 452 | |
| 453 | .. index:: |
| 454 | statement: global |
| 455 | pair: unbinding; name |
| 456 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 457 | Deletion of a name removes the binding of that name from the local or global |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 458 | namespace, depending on whether the name occurs in a :keyword:`global` statement |
| 459 | in the same code block. If the name is unbound, a :exc:`NameError` exception |
| 460 | will be raised. |
| 461 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 462 | .. index:: pair: attribute; deletion |
| 463 | |
| 464 | Deletion of attribute references, subscriptions and slicings is passed to the |
| 465 | primary object involved; deletion of a slicing is in general equivalent to |
| 466 | assignment of an empty slice of the right type (but even this is determined by |
| 467 | the sliced object). |
| 468 | |
Amaury Forgeot d'Arc | ba117ef | 2010-09-10 21:39:53 +0000 | [diff] [blame] | 469 | .. versionchanged:: 3.2 |
| 470 | Previously it was illegal to delete a name from the local namespace if it |
| 471 | occurs as a free variable in a nested block. |
| 472 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 473 | |
| 474 | .. _return: |
| 475 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 476 | The :keyword:`!return` statement |
| 477 | ================================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 478 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 479 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 480 | ! statement: return |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 481 | pair: function; definition |
| 482 | pair: class; definition |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 483 | |
| 484 | .. productionlist:: |
| 485 | return_stmt: "return" [`expression_list`] |
| 486 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 487 | :keyword:`return` may only occur syntactically nested in a function definition, |
| 488 | not within a nested class definition. |
| 489 | |
| 490 | If an expression list is present, it is evaluated, else ``None`` is substituted. |
| 491 | |
| 492 | :keyword:`return` leaves the current function call with the expression list (or |
| 493 | ``None``) as return value. |
| 494 | |
| 495 | .. index:: keyword: finally |
| 496 | |
| 497 | When :keyword:`return` passes control out of a :keyword:`try` statement with a |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 498 | :keyword:`finally` clause, that :keyword:`!finally` clause is executed before |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 499 | really leaving the function. |
| 500 | |
Nick Coghlan | 1f7ce62 | 2012-01-13 21:43:40 +1000 | [diff] [blame] | 501 | In a generator function, the :keyword:`return` statement indicates that the |
| 502 | generator is done and will cause :exc:`StopIteration` to be raised. The returned |
| 503 | value (if any) is used as an argument to construct :exc:`StopIteration` and |
| 504 | becomes the :attr:`StopIteration.value` attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 505 | |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 506 | In an asynchronous generator function, an empty :keyword:`return` statement |
| 507 | indicates that the asynchronous generator is done and will cause |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 508 | :exc:`StopAsyncIteration` to be raised. A non-empty :keyword:`!return` |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 509 | statement is a syntax error in an asynchronous generator function. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 510 | |
| 511 | .. _yield: |
| 512 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 513 | The :keyword:`!yield` statement |
| 514 | =============================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 515 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 516 | .. index:: |
| 517 | statement: yield |
| 518 | single: generator; function |
| 519 | single: generator; iterator |
| 520 | single: function; generator |
| 521 | exception: StopIteration |
| 522 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 523 | .. productionlist:: |
| 524 | yield_stmt: `yield_expression` |
| 525 | |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 526 | A :keyword:`yield` statement is semantically equivalent to a :ref:`yield |
| 527 | expression <yieldexpr>`. The yield statement can be used to omit the parentheses |
| 528 | that would otherwise be required in the equivalent yield expression |
| 529 | statement. For example, the yield statements :: |
Nick Coghlan | 1f7ce62 | 2012-01-13 21:43:40 +1000 | [diff] [blame] | 530 | |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 531 | yield <expr> |
| 532 | yield from <expr> |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 533 | |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 534 | are equivalent to the yield expression statements :: |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 535 | |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 536 | (yield <expr>) |
| 537 | (yield from <expr>) |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 538 | |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 539 | Yield expressions and statements are only used when defining a :term:`generator` |
| 540 | function, and are only used in the body of the generator function. Using yield |
| 541 | in a function definition is sufficient to cause that definition to create a |
| 542 | generator function instead of a normal function. |
Nick Coghlan | 1f7ce62 | 2012-01-13 21:43:40 +1000 | [diff] [blame] | 543 | |
Benjamin Peterson | d1c85fd | 2014-01-26 22:52:08 -0500 | [diff] [blame] | 544 | For full details of :keyword:`yield` semantics, refer to the |
| 545 | :ref:`yieldexpr` section. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 546 | |
| 547 | .. _raise: |
| 548 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 549 | The :keyword:`!raise` statement |
| 550 | =============================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 551 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 552 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 553 | ! statement: raise |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 554 | single: exception |
| 555 | pair: raising; exception |
Georg Brandl | 1aea30a | 2008-07-19 15:51:07 +0000 | [diff] [blame] | 556 | single: __traceback__ (exception attribute) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 557 | |
| 558 | .. productionlist:: |
Georg Brandl | e06de8b | 2008-05-05 21:42:51 +0000 | [diff] [blame] | 559 | raise_stmt: "raise" [`expression` ["from" `expression`]] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 560 | |
| 561 | If no expressions are present, :keyword:`raise` re-raises the last exception |
| 562 | that was active in the current scope. If no exception is active in the current |
Sandro Tosi | b2794c8 | 2012-01-01 12:17:15 +0100 | [diff] [blame] | 563 | scope, a :exc:`RuntimeError` exception is raised indicating that this is an |
| 564 | error. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 565 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 566 | Otherwise, :keyword:`raise` evaluates the first expression as the exception |
| 567 | object. It must be either a subclass or an instance of :class:`BaseException`. |
| 568 | If it is a class, the exception instance will be obtained when needed by |
| 569 | instantiating the class with no arguments. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 570 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 571 | The :dfn:`type` of the exception is the exception instance's class, the |
| 572 | :dfn:`value` is the instance itself. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 573 | |
| 574 | .. index:: object: traceback |
| 575 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 576 | A traceback object is normally created automatically when an exception is raised |
Georg Brandl | e06de8b | 2008-05-05 21:42:51 +0000 | [diff] [blame] | 577 | and attached to it as the :attr:`__traceback__` attribute, which is writable. |
| 578 | You can create an exception and set your own traceback in one step using the |
| 579 | :meth:`with_traceback` exception method (which returns the same exception |
| 580 | instance, with its traceback set to its argument), like so:: |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 581 | |
Benjamin Peterson | b785169 | 2009-02-16 16:15:34 +0000 | [diff] [blame] | 582 | raise Exception("foo occurred").with_traceback(tracebackobj) |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 583 | |
Georg Brandl | 1aea30a | 2008-07-19 15:51:07 +0000 | [diff] [blame] | 584 | .. index:: pair: exception; chaining |
| 585 | __cause__ (exception attribute) |
| 586 | __context__ (exception attribute) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 587 | |
Georg Brandl | 1aea30a | 2008-07-19 15:51:07 +0000 | [diff] [blame] | 588 | The ``from`` clause is used for exception chaining: if given, the second |
| 589 | *expression* must be another exception class or instance, which will then be |
| 590 | attached to the raised exception as the :attr:`__cause__` attribute (which is |
| 591 | writable). If the raised exception is not handled, both exceptions will be |
| 592 | printed:: |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 593 | |
Georg Brandl | 1aea30a | 2008-07-19 15:51:07 +0000 | [diff] [blame] | 594 | >>> try: |
| 595 | ... print(1 / 0) |
| 596 | ... except Exception as exc: |
| 597 | ... raise RuntimeError("Something bad happened") from exc |
| 598 | ... |
| 599 | Traceback (most recent call last): |
| 600 | File "<stdin>", line 2, in <module> |
csabella | 763557e | 2017-05-20 02:48:28 -0400 | [diff] [blame] | 601 | ZeroDivisionError: division by zero |
Georg Brandl | 1aea30a | 2008-07-19 15:51:07 +0000 | [diff] [blame] | 602 | |
| 603 | The above exception was the direct cause of the following exception: |
| 604 | |
| 605 | Traceback (most recent call last): |
| 606 | File "<stdin>", line 4, in <module> |
| 607 | RuntimeError: Something bad happened |
| 608 | |
| 609 | A similar mechanism works implicitly if an exception is raised inside an |
Georg Brandl | a4c8c47 | 2014-10-31 10:38:49 +0100 | [diff] [blame] | 610 | exception handler or a :keyword:`finally` clause: the previous exception is then |
| 611 | attached as the new exception's :attr:`__context__` attribute:: |
Georg Brandl | 1aea30a | 2008-07-19 15:51:07 +0000 | [diff] [blame] | 612 | |
| 613 | >>> try: |
| 614 | ... print(1 / 0) |
| 615 | ... except: |
| 616 | ... raise RuntimeError("Something bad happened") |
| 617 | ... |
| 618 | Traceback (most recent call last): |
| 619 | File "<stdin>", line 2, in <module> |
csabella | 763557e | 2017-05-20 02:48:28 -0400 | [diff] [blame] | 620 | ZeroDivisionError: division by zero |
Georg Brandl | 1aea30a | 2008-07-19 15:51:07 +0000 | [diff] [blame] | 621 | |
| 622 | During handling of the above exception, another exception occurred: |
| 623 | |
| 624 | Traceback (most recent call last): |
| 625 | File "<stdin>", line 4, in <module> |
| 626 | RuntimeError: Something bad happened |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 627 | |
csabella | 763557e | 2017-05-20 02:48:28 -0400 | [diff] [blame] | 628 | Exception chaining can be explicitly suppressed by specifying :const:`None` in |
| 629 | the ``from`` clause:: |
| 630 | |
| 631 | >>> try: |
| 632 | ... print(1 / 0) |
| 633 | ... except: |
| 634 | ... raise RuntimeError("Something bad happened") from None |
| 635 | ... |
| 636 | Traceback (most recent call last): |
| 637 | File "<stdin>", line 4, in <module> |
| 638 | RuntimeError: Something bad happened |
| 639 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 640 | Additional information on exceptions can be found in section :ref:`exceptions`, |
| 641 | and information about handling exceptions is in section :ref:`try`. |
| 642 | |
csabella | 763557e | 2017-05-20 02:48:28 -0400 | [diff] [blame] | 643 | .. versionchanged:: 3.3 |
Mariatta | 9efad1e | 2017-05-30 15:26:42 -0700 | [diff] [blame] | 644 | :const:`None` is now permitted as ``Y`` in ``raise X from Y``. |
csabella | 763557e | 2017-05-20 02:48:28 -0400 | [diff] [blame] | 645 | |
| 646 | .. versionadded:: 3.3 |
| 647 | The ``__suppress_context__`` attribute to suppress automatic display of the |
Mariatta | 9efad1e | 2017-05-30 15:26:42 -0700 | [diff] [blame] | 648 | exception context. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 649 | |
| 650 | .. _break: |
| 651 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 652 | The :keyword:`!break` statement |
| 653 | =============================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 654 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 655 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 656 | ! statement: break |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 657 | statement: for |
| 658 | statement: while |
| 659 | pair: loop; statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 660 | |
| 661 | .. productionlist:: |
| 662 | break_stmt: "break" |
| 663 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 664 | :keyword:`break` may only occur syntactically nested in a :keyword:`for` or |
| 665 | :keyword:`while` loop, but not nested in a function or class definition within |
| 666 | that loop. |
| 667 | |
| 668 | .. index:: keyword: else |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 669 | pair: loop control; target |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 670 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 671 | It terminates the nearest enclosing loop, skipping the optional :keyword:`!else` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 672 | clause if the loop has one. |
| 673 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 674 | If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control |
| 675 | target keeps its current value. |
| 676 | |
| 677 | .. index:: keyword: finally |
| 678 | |
| 679 | When :keyword:`break` passes control out of a :keyword:`try` statement with a |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 680 | :keyword:`finally` clause, that :keyword:`!finally` clause is executed before |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 681 | really leaving the loop. |
| 682 | |
| 683 | |
| 684 | .. _continue: |
| 685 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 686 | The :keyword:`!continue` statement |
| 687 | ================================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 688 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 689 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 690 | ! statement: continue |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 691 | statement: for |
| 692 | statement: while |
| 693 | pair: loop; statement |
| 694 | keyword: finally |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 695 | |
| 696 | .. productionlist:: |
| 697 | continue_stmt: "continue" |
| 698 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 699 | :keyword:`continue` may only occur syntactically nested in a :keyword:`for` or |
Serhiy Storchaka | fe2bbb1 | 2018-03-18 09:56:52 +0200 | [diff] [blame] | 700 | :keyword:`while` loop, but not nested in a function or class definition within |
| 701 | that loop. It continues with the next cycle of the nearest enclosing loop. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 702 | |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 703 | When :keyword:`continue` passes control out of a :keyword:`try` statement with a |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 704 | :keyword:`finally` clause, that :keyword:`!finally` clause is executed before |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 705 | really starting the next loop cycle. |
| 706 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 707 | |
| 708 | .. _import: |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 709 | .. _from: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 710 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 711 | The :keyword:`!import` statement |
| 712 | ================================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 713 | |
| 714 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 715 | ! statement: import |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 716 | single: module; importing |
| 717 | pair: name; binding |
| 718 | keyword: from |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 719 | keyword: as |
| 720 | exception: ImportError |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 721 | single: , (comma); import statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 722 | |
| 723 | .. productionlist:: |
Andrés Delfino | caccca78 | 2018-07-07 17:24:46 -0300 | [diff] [blame] | 724 | import_stmt: "import" `module` ["as" `identifier`] ("," `module` ["as" `identifier`])* |
| 725 | : | "from" `relative_module` "import" `identifier` ["as" `identifier`] |
| 726 | : ("," `identifier` ["as" `identifier`])* |
| 727 | : | "from" `relative_module` "import" "(" `identifier` ["as" `identifier`] |
| 728 | : ("," `identifier` ["as" `identifier`])* [","] ")" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 729 | : | "from" `module` "import" "*" |
| 730 | module: (`identifier` ".")* `identifier` |
| 731 | relative_module: "."* `module` | "."+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 732 | |
Nick Coghlan | e3376ef | 2012-08-02 22:02:35 +1000 | [diff] [blame] | 733 | The basic import statement (no :keyword:`from` clause) is executed in two |
| 734 | steps: |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 735 | |
Nick Coghlan | e3376ef | 2012-08-02 22:02:35 +1000 | [diff] [blame] | 736 | #. find a module, loading and initializing it if necessary |
| 737 | #. define a name or names in the local namespace for the scope where |
| 738 | the :keyword:`import` statement occurs. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 739 | |
Nick Coghlan | e3376ef | 2012-08-02 22:02:35 +1000 | [diff] [blame] | 740 | When the statement contains multiple clauses (separated by |
| 741 | commas) the two steps are carried out separately for each clause, just |
Ned Deily | cec9581 | 2016-05-17 21:44:46 -0400 | [diff] [blame] | 742 | as though the clauses had been separated out into individual import |
Nick Coghlan | e3376ef | 2012-08-02 22:02:35 +1000 | [diff] [blame] | 743 | statements. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 744 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 745 | The details of the first step, finding and loading modules are described in |
Nick Coghlan | e3376ef | 2012-08-02 22:02:35 +1000 | [diff] [blame] | 746 | greater detail in the section on the :ref:`import system <importsystem>`, |
| 747 | which also describes the various types of packages and modules that can |
| 748 | be imported, as well as all the hooks that can be used to customize |
| 749 | the import system. Note that failures in this step may indicate either |
| 750 | that the module could not be located, *or* that an error occurred while |
| 751 | initializing the module, which includes execution of the module's code. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 752 | |
Nick Coghlan | e3376ef | 2012-08-02 22:02:35 +1000 | [diff] [blame] | 753 | If the requested module is retrieved successfully, it will be made |
| 754 | available in the local namespace in one of three ways: |
| 755 | |
Terry Jan Reedy | 7c895ed | 2014-04-29 00:58:56 -0400 | [diff] [blame] | 756 | .. index:: single: as; import statement |
| 757 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 758 | * If the module name is followed by :keyword:`!as`, then the name |
| 759 | following :keyword:`!as` is bound directly to the imported module. |
Nick Coghlan | e3376ef | 2012-08-02 22:02:35 +1000 | [diff] [blame] | 760 | * If no other name is specified, and the module being imported is a top |
| 761 | level module, the module's name is bound in the local namespace as a |
| 762 | reference to the imported module |
| 763 | * If the module being imported is *not* a top level module, then the name |
| 764 | of the top level package that contains the module is bound in the local |
| 765 | namespace as a reference to the top level package. The imported module |
| 766 | must be accessed using its full qualified name rather than directly |
| 767 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 768 | |
| 769 | .. index:: |
| 770 | pair: name; binding |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 771 | single: from; import statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 772 | |
Nick Coghlan | e3376ef | 2012-08-02 22:02:35 +1000 | [diff] [blame] | 773 | The :keyword:`from` form uses a slightly more complex process: |
| 774 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 775 | #. find the module specified in the :keyword:`from` clause, loading and |
Nick Coghlan | e3376ef | 2012-08-02 22:02:35 +1000 | [diff] [blame] | 776 | initializing it if necessary; |
| 777 | #. for each of the identifiers specified in the :keyword:`import` clauses: |
| 778 | |
| 779 | #. check if the imported module has an attribute by that name |
| 780 | #. if not, attempt to import a submodule with that name and then |
| 781 | check the imported module again for that attribute |
| 782 | #. if the attribute is not found, :exc:`ImportError` is raised. |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 783 | #. otherwise, a reference to that value is stored in the local namespace, |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 784 | using the name in the :keyword:`!as` clause if it is present, |
Nick Coghlan | e3376ef | 2012-08-02 22:02:35 +1000 | [diff] [blame] | 785 | otherwise using the attribute name |
| 786 | |
| 787 | Examples:: |
| 788 | |
| 789 | import foo # foo imported and bound locally |
| 790 | import foo.bar.baz # foo.bar.baz imported, foo bound locally |
| 791 | import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb |
| 792 | from foo.bar import baz # foo.bar.baz imported and bound as baz |
| 793 | from foo import attr # foo imported and foo.attr bound as attr |
| 794 | |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 795 | .. index:: single: * (asterisk); import statement |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 796 | |
Nick Coghlan | e3376ef | 2012-08-02 22:02:35 +1000 | [diff] [blame] | 797 | If the list of identifiers is replaced by a star (``'*'``), all public |
| 798 | names defined in the module are bound in the local namespace for the scope |
| 799 | where the :keyword:`import` statement occurs. |
| 800 | |
| 801 | .. index:: single: __all__ (optional module attribute) |
| 802 | |
| 803 | The *public names* defined by a module are determined by checking the module's |
| 804 | namespace for a variable named ``__all__``; if defined, it must be a sequence |
| 805 | of strings which are names defined or imported by that module. The names |
| 806 | given in ``__all__`` are all considered public and are required to exist. If |
| 807 | ``__all__`` is not defined, the set of public names includes all names found |
| 808 | in the module's namespace which do not begin with an underscore character |
| 809 | (``'_'``). ``__all__`` should contain the entire public API. It is intended |
| 810 | to avoid accidentally exporting items that are not part of the API (such as |
| 811 | library modules which were imported and used within the module). |
| 812 | |
Georg Brandl | a4c8c47 | 2014-10-31 10:38:49 +0100 | [diff] [blame] | 813 | The wild card form of import --- ``from module import *`` --- is only allowed at |
| 814 | the module level. Attempting to use it in class or function definitions will |
| 815 | raise a :exc:`SyntaxError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 816 | |
| 817 | .. index:: |
Brett Cannon | e43b060 | 2009-03-21 03:11:16 +0000 | [diff] [blame] | 818 | single: relative; import |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 819 | |
Brett Cannon | e43b060 | 2009-03-21 03:11:16 +0000 | [diff] [blame] | 820 | When specifying what module to import you do not have to specify the absolute |
| 821 | name of the module. When a module or package is contained within another |
| 822 | package it is possible to make a relative import within the same top package |
| 823 | without having to mention the package name. By using leading dots in the |
| 824 | specified module or package after :keyword:`from` you can specify how high to |
| 825 | traverse up the current package hierarchy without specifying exact names. One |
| 826 | leading dot means the current package where the module making the import |
| 827 | exists. Two dots means up one package level. Three dots is up two levels, etc. |
| 828 | So if you execute ``from . import mod`` from a module in the ``pkg`` package |
| 829 | then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2 |
Florent Xicluna | 0c8414e | 2010-09-03 20:23:40 +0000 | [diff] [blame] | 830 | import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``. |
Brett Cannon | e43b060 | 2009-03-21 03:11:16 +0000 | [diff] [blame] | 831 | The specification for relative imports is contained within :pep:`328`. |
Georg Brandl | 5b318c0 | 2008-08-03 09:47:27 +0000 | [diff] [blame] | 832 | |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 833 | :func:`importlib.import_module` is provided to support applications that |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 834 | determine dynamically the modules to be loaded. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 835 | |
| 836 | |
| 837 | .. _future: |
| 838 | |
| 839 | Future statements |
| 840 | ----------------- |
| 841 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 842 | .. index:: |
| 843 | pair: future; statement |
| 844 | single: __future__; future statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 845 | |
| 846 | A :dfn:`future statement` is a directive to the compiler that a particular |
| 847 | module should be compiled using syntax or semantics that will be available in a |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 848 | specified future release of Python where the feature becomes standard. |
| 849 | |
| 850 | The future statement is intended to ease migration to future versions of Python |
| 851 | that introduce incompatible changes to the language. It allows use of the new |
| 852 | features on a per-module basis before the release in which the feature becomes |
| 853 | standard. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 854 | |
| 855 | .. productionlist:: * |
Andrés Delfino | caccca78 | 2018-07-07 17:24:46 -0300 | [diff] [blame] | 856 | future_stmt: "from" "__future__" "import" `feature` ["as" `identifier`] |
| 857 | : ("," `feature` ["as" `identifier`])* |
| 858 | : | "from" "__future__" "import" "(" `feature` ["as" `identifier`] |
| 859 | : ("," `feature` ["as" `identifier`])* [","] ")" |
| 860 | feature: `identifier` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 861 | |
| 862 | A future statement must appear near the top of the module. The only lines that |
| 863 | can appear before a future statement are: |
| 864 | |
| 865 | * the module docstring (if any), |
| 866 | * comments, |
| 867 | * blank lines, and |
| 868 | * other future statements. |
| 869 | |
Guido van Rossum | 95e4d58 | 2018-01-26 08:20:18 -0800 | [diff] [blame] | 870 | The only feature in Python 3.7 that requires using the future statement is |
| 871 | ``annotations``. |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 872 | |
Guido van Rossum | 95e4d58 | 2018-01-26 08:20:18 -0800 | [diff] [blame] | 873 | All historical features enabled by the future statement are still recognized |
| 874 | by Python 3. The list includes ``absolute_import``, ``division``, |
| 875 | ``generators``, ``generator_stop``, ``unicode_literals``, |
| 876 | ``print_function``, ``nested_scopes`` and ``with_statement``. They are |
| 877 | all redundant because they are always enabled, and only kept for |
| 878 | backwards compatibility. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 879 | |
| 880 | A future statement is recognized and treated specially at compile time: Changes |
| 881 | to the semantics of core constructs are often implemented by generating |
| 882 | different code. It may even be the case that a new feature introduces new |
| 883 | incompatible syntax (such as a new reserved word), in which case the compiler |
| 884 | may need to parse the module differently. Such decisions cannot be pushed off |
| 885 | until runtime. |
| 886 | |
| 887 | For any given release, the compiler knows which feature names have been defined, |
| 888 | and raises a compile-time error if a future statement contains a feature not |
| 889 | known to it. |
| 890 | |
| 891 | The direct runtime semantics are the same as for any import statement: there is |
| 892 | a standard module :mod:`__future__`, described later, and it will be imported in |
| 893 | the usual way at the time the future statement is executed. |
| 894 | |
| 895 | The interesting runtime semantics depend on the specific feature enabled by the |
| 896 | future statement. |
| 897 | |
| 898 | Note that there is nothing special about the statement:: |
| 899 | |
| 900 | import __future__ [as name] |
| 901 | |
| 902 | That is not a future statement; it's an ordinary import statement with no |
| 903 | special semantics or syntax restrictions. |
| 904 | |
Georg Brandl | 22b3431 | 2009-07-26 14:54:51 +0000 | [diff] [blame] | 905 | Code compiled by calls to the built-in functions :func:`exec` and :func:`compile` |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 906 | that occur in a module :mod:`M` containing a future statement will, by default, |
| 907 | use the new syntax or semantics associated with the future statement. This can |
| 908 | be controlled by optional arguments to :func:`compile` --- see the documentation |
| 909 | of that function for details. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 910 | |
| 911 | A future statement typed at an interactive interpreter prompt will take effect |
| 912 | for the rest of the interpreter session. If an interpreter is started with the |
| 913 | :option:`-i` option, is passed a script name to execute, and the script includes |
| 914 | a future statement, it will be in effect in the interactive session started |
| 915 | after the script is executed. |
| 916 | |
Georg Brandl | ff2ad0e | 2009-04-27 16:51:45 +0000 | [diff] [blame] | 917 | .. seealso:: |
| 918 | |
| 919 | :pep:`236` - Back to the __future__ |
| 920 | The original proposal for the __future__ mechanism. |
| 921 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 922 | |
| 923 | .. _global: |
| 924 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 925 | The :keyword:`!global` statement |
| 926 | ================================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 927 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 928 | .. index:: |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 929 | ! statement: global |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 930 | triple: global; name; binding |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 931 | single: , (comma); identifier list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 932 | |
| 933 | .. productionlist:: |
| 934 | global_stmt: "global" `identifier` ("," `identifier`)* |
| 935 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 936 | The :keyword:`global` statement is a declaration which holds for the entire |
| 937 | current code block. It means that the listed identifiers are to be interpreted |
| 938 | as globals. It would be impossible to assign to a global variable without |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 939 | :keyword:`!global`, although free variables may refer to globals without being |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 940 | declared global. |
| 941 | |
| 942 | Names listed in a :keyword:`global` statement must not be used in the same code |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 943 | block textually preceding that :keyword:`!global` statement. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 944 | |
| 945 | Names listed in a :keyword:`global` statement must not be defined as formal |
| 946 | parameters or in a :keyword:`for` loop control target, :keyword:`class` |
Guido van Rossum | 6cff874 | 2016-09-09 09:36:26 -0700 | [diff] [blame] | 947 | definition, function definition, :keyword:`import` statement, or variable |
| 948 | annotation. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 949 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 950 | .. impl-detail:: |
| 951 | |
kms70847 | 8d59aca | 2017-09-28 15:54:48 -0400 | [diff] [blame] | 952 | The current implementation does not enforce some of these restrictions, but |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 953 | programs should not abuse this freedom, as future implementations may enforce |
| 954 | them or silently change the meaning of the program. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 955 | |
| 956 | .. index:: |
| 957 | builtin: exec |
| 958 | builtin: eval |
| 959 | builtin: compile |
| 960 | |
Jim Fasarakis-Hilliard | f34c6850 | 2017-05-08 14:36:29 +0300 | [diff] [blame] | 961 | **Programmer's note:** :keyword:`global` is a directive to the parser. It |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 962 | applies only to code parsed at the same time as the :keyword:`!global` statement. |
| 963 | In particular, a :keyword:`!global` statement contained in a string or code |
Georg Brandl | c4a55fc | 2010-02-06 18:46:57 +0000 | [diff] [blame] | 964 | object supplied to the built-in :func:`exec` function does not affect the code |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 965 | block *containing* the function call, and code contained in such a string is |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 966 | unaffected by :keyword:`!global` statements in the code containing the function |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 967 | call. The same applies to the :func:`eval` and :func:`compile` functions. |
| 968 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 969 | |
| 970 | .. _nonlocal: |
| 971 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 972 | The :keyword:`!nonlocal` statement |
| 973 | ================================== |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 974 | |
| 975 | .. index:: statement: nonlocal |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 976 | single: , (comma); identifier list |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 977 | |
| 978 | .. productionlist:: |
| 979 | nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)* |
| 980 | |
Georg Brandl | c5d98b4 | 2007-12-04 18:11:03 +0000 | [diff] [blame] | 981 | .. XXX add when implemented |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 982 | : ["=" (`target_list` "=")+ starred_expression] |
Georg Brandl | 06788c9 | 2009-01-03 21:31:47 +0000 | [diff] [blame] | 983 | : | "nonlocal" identifier augop expression_list |
Georg Brandl | c5d98b4 | 2007-12-04 18:11:03 +0000 | [diff] [blame] | 984 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 985 | The :keyword:`nonlocal` statement causes the listed identifiers to refer to |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 986 | previously bound variables in the nearest enclosing scope excluding globals. |
| 987 | This is important because the default behavior for binding is to search the |
| 988 | local namespace first. The statement allows encapsulated code to rebind |
| 989 | variables outside of the local scope besides the global (module) scope. |
Georg Brandl | c5d98b4 | 2007-12-04 18:11:03 +0000 | [diff] [blame] | 990 | |
Georg Brandl | c5d98b4 | 2007-12-04 18:11:03 +0000 | [diff] [blame] | 991 | .. XXX not implemented |
| 992 | The :keyword:`nonlocal` statement may prepend an assignment or augmented |
| 993 | assignment, but not an expression. |
| 994 | |
Raymond Hettinger | aa7886d | 2014-05-26 22:20:37 -0700 | [diff] [blame] | 995 | Names listed in a :keyword:`nonlocal` statement, unlike those listed in a |
Georg Brandl | c5d98b4 | 2007-12-04 18:11:03 +0000 | [diff] [blame] | 996 | :keyword:`global` statement, must refer to pre-existing bindings in an |
| 997 | enclosing scope (the scope in which a new binding should be created cannot |
| 998 | be determined unambiguously). |
| 999 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1000 | Names listed in a :keyword:`nonlocal` statement must not collide with |
Georg Brandl | c5d98b4 | 2007-12-04 18:11:03 +0000 | [diff] [blame] | 1001 | pre-existing bindings in the local scope. |
| 1002 | |
| 1003 | .. seealso:: |
| 1004 | |
| 1005 | :pep:`3104` - Access to Names in Outer Scopes |
| 1006 | The specification for the :keyword:`nonlocal` statement. |