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