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