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 | |
| 36 | .. index:: pair: expression; statement |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 37 | .. index:: pair: expression; list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 38 | |
| 39 | Expression statements are used (mostly interactively) to compute and write a |
| 40 | value, or (usually) to call a procedure (a function that returns no meaningful |
| 41 | result; in Python, procedures return the value ``None``). Other uses of |
| 42 | expression statements are allowed and occasionally useful. The syntax for an |
| 43 | expression statement is: |
| 44 | |
| 45 | .. productionlist:: |
| 46 | expression_stmt: `expression_list` |
| 47 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 48 | An expression statement evaluates the expression list (which may be a single |
| 49 | expression). |
| 50 | |
| 51 | .. index:: |
| 52 | builtin: repr |
| 53 | object: None |
| 54 | pair: string; conversion |
| 55 | single: output |
| 56 | pair: standard; output |
| 57 | pair: writing; values |
| 58 | pair: procedure; call |
| 59 | |
| 60 | In interactive mode, if the value is not ``None``, it is converted to a string |
| 61 | 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] | 62 | standard output on a line by itself (except if the result is ``None``, so that |
| 63 | procedure calls do not cause any output.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 64 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 65 | .. _assignment: |
| 66 | |
| 67 | Assignment statements |
| 68 | ===================== |
| 69 | |
| 70 | .. index:: |
| 71 | pair: assignment; statement |
| 72 | pair: binding; name |
| 73 | pair: rebinding; name |
| 74 | object: mutable |
| 75 | pair: attribute; assignment |
| 76 | |
| 77 | Assignment statements are used to (re)bind names to values and to modify |
| 78 | attributes or items of mutable objects: |
| 79 | |
| 80 | .. productionlist:: |
| 81 | assignment_stmt: (`target_list` "=")+ (`expression_list` | `yield_expression`) |
| 82 | target_list: `target` ("," `target`)* [","] |
| 83 | target: `identifier` |
| 84 | : | "(" `target_list` ")" |
| 85 | : | "[" `target_list` "]" |
| 86 | : | `attributeref` |
| 87 | : | `subscription` |
| 88 | : | `slicing` |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 89 | : | "*" `target` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 90 | |
| 91 | (See section :ref:`primaries` for the syntax definitions for the last three |
| 92 | symbols.) |
| 93 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 94 | An assignment statement evaluates the expression list (remember that this can be |
| 95 | a single expression or a comma-separated list, the latter yielding a tuple) and |
| 96 | assigns the single resulting object to each of the target lists, from left to |
| 97 | right. |
| 98 | |
| 99 | .. index:: |
| 100 | single: target |
| 101 | pair: target; list |
| 102 | |
| 103 | Assignment is defined recursively depending on the form of the target (list). |
| 104 | When a target is part of a mutable object (an attribute reference, subscription |
| 105 | or slicing), the mutable object must ultimately perform the assignment and |
| 106 | decide about its validity, and may raise an exception if the assignment is |
| 107 | unacceptable. The rules observed by various types and the exceptions raised are |
| 108 | given with the definition of the object types (see section :ref:`types`). |
| 109 | |
| 110 | .. index:: triple: target; list; assignment |
| 111 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 112 | Assignment of an object to a target list, optionally enclosed in parentheses or |
| 113 | square brackets, is recursively defined as follows. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 114 | |
| 115 | * If the target list is a single target: The object is assigned to that target. |
| 116 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 117 | * If the target list is a comma-separated list of targets: |
| 118 | |
| 119 | * If the target list contains one target prefixed with an asterisk, called a |
| 120 | "starred" target: The object must be a sequence with at least as many items |
| 121 | as there are targets in the target list, minus one. The first items of the |
| 122 | sequence are assigned, from left to right, to the targets before the starred |
| 123 | target. The final items of the sequence are assigned to the targets after |
| 124 | the starred target. A list of the remaining items in the sequence is then |
| 125 | assigned to the starred target (the list can be empty). |
| 126 | |
| 127 | * Else: The object must be a sequence with the same number of items as there |
| 128 | are targets in the target list, and the items are assigned, from left to |
| 129 | right, to the corresponding targets. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 130 | |
| 131 | Assignment of an object to a single target is recursively defined as follows. |
| 132 | |
| 133 | * If the target is an identifier (name): |
| 134 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 135 | * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal` |
| 136 | statement in the current code block: the name is bound to the object in the |
| 137 | current local namespace. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 138 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 139 | * Otherwise: the name is bound to the object in the global namespace or the |
| 140 | outer namespace determined by :keyword:`nonlocal`, respectively. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 141 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 142 | The name is rebound if it was already bound. This may cause the reference |
| 143 | count for the object previously bound to the name to reach zero, causing the |
| 144 | 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] | 145 | |
| 146 | * If the target is an attribute reference: The primary expression in the |
| 147 | reference is evaluated. It should yield an object with assignable attributes; |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 148 | if this is not the case, :exc:`TypeError` is raised. That object is then |
| 149 | asked to assign the assigned object to the given attribute; if it cannot |
| 150 | perform the assignment, it raises an exception (usually but not necessarily |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 151 | :exc:`AttributeError`). |
| 152 | |
| 153 | .. index:: |
| 154 | pair: subscription; assignment |
| 155 | object: mutable |
| 156 | |
| 157 | * 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] | 158 | evaluated. It should yield either a mutable sequence object (such as a list) |
| 159 | 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] | 160 | evaluated. |
| 161 | |
| 162 | .. index:: |
| 163 | object: sequence |
| 164 | object: list |
| 165 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 166 | If the primary is a mutable sequence object (such as a list), the subscript |
| 167 | must yield an integer. If it is negative, the sequence's length is added to |
| 168 | it. The resulting value must be a nonnegative integer less than the |
| 169 | sequence's length, and the sequence is asked to assign the assigned object to |
| 170 | its item with that index. If the index is out of range, :exc:`IndexError` is |
| 171 | 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] | 172 | |
| 173 | .. index:: |
| 174 | object: mapping |
| 175 | object: dictionary |
| 176 | |
| 177 | If the primary is a mapping object (such as a dictionary), the subscript must |
| 178 | have a type compatible with the mapping's key type, and the mapping is then |
| 179 | asked to create a key/datum pair which maps the subscript to the assigned |
| 180 | object. This can either replace an existing key/value pair with the same key |
| 181 | value, or insert a new key/value pair (if no key with the same value existed). |
| 182 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 183 | For user-defined objects, the :meth:`__setitem__` method is called with |
| 184 | appropriate arguments. |
| 185 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 186 | .. index:: pair: slicing; assignment |
| 187 | |
| 188 | * If the target is a slicing: The primary expression in the reference is |
| 189 | evaluated. It should yield a mutable sequence object (such as a list). The |
| 190 | assigned object should be a sequence object of the same type. Next, the lower |
| 191 | and upper bound expressions are evaluated, insofar they are present; defaults |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 192 | are zero and the sequence's length. The bounds should evaluate to integers. |
| 193 | If either bound is negative, the sequence's length is added to it. The |
| 194 | resulting bounds are clipped to lie between zero and the sequence's length, |
| 195 | inclusive. Finally, the sequence object is asked to replace the slice with |
| 196 | the items of the assigned sequence. The length of the slice may be different |
| 197 | from the length of the assigned sequence, thus changing the length of the |
| 198 | target sequence, if the object allows it. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 199 | |
| 200 | (In the current implementation, the syntax for targets is taken to be the same |
| 201 | as for expressions, and invalid syntax is rejected during the code generation |
| 202 | phase, causing less detailed error messages.) |
| 203 | |
| 204 | WARNING: Although the definition of assignment implies that overlaps between the |
| 205 | left-hand side and the right-hand side are 'safe' (for example ``a, b = b, a`` |
| 206 | swaps two variables), overlaps *within* the collection of assigned-to variables |
| 207 | are not safe! For instance, the following program prints ``[0, 2]``:: |
| 208 | |
| 209 | x = [0, 1] |
| 210 | i = 0 |
| 211 | i, x[i] = 1, 2 |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 212 | print(x) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 213 | |
| 214 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 215 | .. seealso:: |
| 216 | |
| 217 | :pep:`3132` - Extended Iterable Unpacking |
| 218 | The specification for the ``*target`` feature. |
| 219 | |
| 220 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 221 | .. _augassign: |
| 222 | |
| 223 | Augmented assignment statements |
| 224 | ------------------------------- |
| 225 | |
| 226 | .. index:: |
| 227 | pair: augmented; assignment |
| 228 | single: statement; assignment, augmented |
| 229 | |
| 230 | Augmented assignment is the combination, in a single statement, of a binary |
| 231 | operation and an assignment statement: |
| 232 | |
| 233 | .. productionlist:: |
| 234 | augmented_assignment_stmt: `target` `augop` (`expression_list` | `yield_expression`) |
| 235 | augop: "+=" | "-=" | "*=" | "/=" | "%=" | "**=" |
| 236 | : | ">>=" | "<<=" | "&=" | "^=" | "|=" |
| 237 | |
| 238 | (See section :ref:`primaries` for the syntax definitions for the last three |
| 239 | symbols.) |
| 240 | |
| 241 | An augmented assignment evaluates the target (which, unlike normal assignment |
| 242 | statements, cannot be an unpacking) and the expression list, performs the binary |
| 243 | operation specific to the type of assignment on the two operands, and assigns |
| 244 | the result to the original target. The target is only evaluated once. |
| 245 | |
| 246 | An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x + |
| 247 | 1`` to achieve a similar, but not exactly equal effect. In the augmented |
| 248 | version, ``x`` is only evaluated once. Also, when possible, the actual operation |
| 249 | is performed *in-place*, meaning that rather than creating a new object and |
| 250 | assigning that to the target, the old object is modified instead. |
| 251 | |
| 252 | With the exception of assigning to tuples and multiple targets in a single |
| 253 | statement, the assignment done by augmented assignment statements is handled the |
| 254 | same way as normal assignments. Similarly, with the exception of the possible |
| 255 | *in-place* behavior, the binary operation performed by augmented assignment is |
| 256 | the same as the normal binary operations. |
| 257 | |
| 258 | For targets which are attribute references, the initial value is retrieved with |
| 259 | a :meth:`getattr` and the result is assigned with a :meth:`setattr`. Notice |
| 260 | that the two methods do not necessarily refer to the same variable. When |
| 261 | :meth:`getattr` refers to a class variable, :meth:`setattr` still writes to an |
| 262 | instance variable. For example:: |
| 263 | |
| 264 | class A: |
| 265 | x = 3 # class variable |
| 266 | a = A() |
| 267 | a.x += 1 # writes a.x as 4 leaving A.x as 3 |
| 268 | |
| 269 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 270 | .. _assert: |
| 271 | |
| 272 | The :keyword:`assert` statement |
| 273 | =============================== |
| 274 | |
| 275 | .. index:: |
| 276 | statement: assert |
| 277 | pair: debugging; assertions |
| 278 | |
| 279 | Assert statements are a convenient way to insert debugging assertions into a |
| 280 | program: |
| 281 | |
| 282 | .. productionlist:: |
| 283 | assert_stmt: "assert" `expression` ["," `expression`] |
| 284 | |
| 285 | The simple form, ``assert expression``, is equivalent to :: |
| 286 | |
| 287 | if __debug__: |
| 288 | if not expression: raise AssertionError |
| 289 | |
| 290 | The extended form, ``assert expression1, expression2``, is equivalent to :: |
| 291 | |
| 292 | if __debug__: |
Georg Brandl | 18a499d | 2007-12-29 10:57:11 +0000 | [diff] [blame^] | 293 | if not expression1: raise AssertionError(expression2) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 294 | |
| 295 | .. index:: |
| 296 | single: __debug__ |
| 297 | exception: AssertionError |
| 298 | |
| 299 | These equivalences assume that ``__debug__`` and :exc:`AssertionError` refer to |
| 300 | the built-in variables with those names. In the current implementation, the |
| 301 | built-in variable ``__debug__`` is ``True`` under normal circumstances, |
| 302 | ``False`` when optimization is requested (command line option -O). The current |
| 303 | code generator emits no code for an assert statement when optimization is |
| 304 | requested at compile time. Note that it is unnecessary to include the source |
| 305 | code for the expression that failed in the error message; it will be displayed |
| 306 | as part of the stack trace. |
| 307 | |
| 308 | Assignments to ``__debug__`` are illegal. The value for the built-in variable |
| 309 | is determined when the interpreter starts. |
| 310 | |
| 311 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 312 | .. _pass: |
| 313 | |
| 314 | The :keyword:`pass` statement |
| 315 | ============================= |
| 316 | |
| 317 | .. index:: statement: pass |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 318 | pair: null; operation |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 319 | |
| 320 | .. productionlist:: |
| 321 | pass_stmt: "pass" |
| 322 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 323 | :keyword:`pass` is a null operation --- when it is executed, nothing happens. |
| 324 | It is useful as a placeholder when a statement is required syntactically, but no |
| 325 | code needs to be executed, for example:: |
| 326 | |
| 327 | def f(arg): pass # a function that does nothing (yet) |
| 328 | |
| 329 | class C: pass # a class with no methods (yet) |
| 330 | |
| 331 | |
| 332 | .. _del: |
| 333 | |
| 334 | The :keyword:`del` statement |
| 335 | ============================ |
| 336 | |
| 337 | .. index:: statement: del |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 338 | pair: deletion; target |
| 339 | triple: deletion; target; list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 340 | |
| 341 | .. productionlist:: |
| 342 | del_stmt: "del" `target_list` |
| 343 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 344 | Deletion is recursively defined very similar to the way assignment is defined. |
| 345 | Rather that spelling it out in full details, here are some hints. |
| 346 | |
| 347 | Deletion of a target list recursively deletes each target, from left to right. |
| 348 | |
| 349 | .. index:: |
| 350 | statement: global |
| 351 | pair: unbinding; name |
| 352 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 353 | 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] | 354 | namespace, depending on whether the name occurs in a :keyword:`global` statement |
| 355 | in the same code block. If the name is unbound, a :exc:`NameError` exception |
| 356 | will be raised. |
| 357 | |
| 358 | .. index:: pair: free; variable |
| 359 | |
| 360 | It is illegal to delete a name from the local namespace if it occurs as a free |
| 361 | variable in a nested block. |
| 362 | |
| 363 | .. index:: pair: attribute; deletion |
| 364 | |
| 365 | Deletion of attribute references, subscriptions and slicings is passed to the |
| 366 | primary object involved; deletion of a slicing is in general equivalent to |
| 367 | assignment of an empty slice of the right type (but even this is determined by |
| 368 | the sliced object). |
| 369 | |
| 370 | |
| 371 | .. _return: |
| 372 | |
| 373 | The :keyword:`return` statement |
| 374 | =============================== |
| 375 | |
| 376 | .. index:: statement: return |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 377 | pair: function; definition |
| 378 | pair: class; definition |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 379 | |
| 380 | .. productionlist:: |
| 381 | return_stmt: "return" [`expression_list`] |
| 382 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 383 | :keyword:`return` may only occur syntactically nested in a function definition, |
| 384 | not within a nested class definition. |
| 385 | |
| 386 | If an expression list is present, it is evaluated, else ``None`` is substituted. |
| 387 | |
| 388 | :keyword:`return` leaves the current function call with the expression list (or |
| 389 | ``None``) as return value. |
| 390 | |
| 391 | .. index:: keyword: finally |
| 392 | |
| 393 | When :keyword:`return` passes control out of a :keyword:`try` statement with a |
| 394 | :keyword:`finally` clause, that :keyword:`finally` clause is executed before |
| 395 | really leaving the function. |
| 396 | |
| 397 | In a generator function, the :keyword:`return` statement is not allowed to |
| 398 | include an :token:`expression_list`. In that context, a bare :keyword:`return` |
| 399 | indicates that the generator is done and will cause :exc:`StopIteration` to be |
| 400 | raised. |
| 401 | |
| 402 | |
| 403 | .. _yield: |
| 404 | |
| 405 | The :keyword:`yield` statement |
| 406 | ============================== |
| 407 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 408 | .. productionlist:: |
| 409 | yield_stmt: `yield_expression` |
| 410 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 411 | The yield statement is nothing but a yield expression used as a statement, |
| 412 | see :ref:`yieldexpr`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 413 | |
| 414 | |
| 415 | .. _raise: |
| 416 | |
| 417 | The :keyword:`raise` statement |
| 418 | ============================== |
| 419 | |
| 420 | .. index:: statement: raise |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 421 | pair: raising; exception |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 422 | |
| 423 | .. productionlist:: |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 424 | raise_stmt: "raise" [`expression` ["from" `expression`]] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 425 | |
| 426 | If no expressions are present, :keyword:`raise` re-raises the last exception |
| 427 | that was active in the current scope. If no exception is active in the current |
| 428 | scope, a :exc:`TypeError` exception is raised indicating that this is an error |
| 429 | (if running under IDLE, a :exc:`Queue.Empty` exception is raised instead). |
| 430 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 431 | Otherwise, :keyword:`raise` evaluates the first expression as the exception |
| 432 | object. It must be either a subclass or an instance of :class:`BaseException`. |
| 433 | If it is a class, the exception instance will be obtained when needed by |
| 434 | instantiating the class with no arguments. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 435 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 436 | The :dfn:`type` of the exception is the exception instance's class, the |
| 437 | :dfn:`value` is the instance itself. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 438 | |
| 439 | .. index:: object: traceback |
| 440 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 441 | A traceback object is normally created automatically when an exception is raised |
| 442 | and attached to it as the :attr:`__traceback__` attribute; however, you can set |
| 443 | your own traceback using the :meth:`with_traceback` exception method, like so:: |
| 444 | |
| 445 | raise RuntimeError("foo occurred").with_traceback(tracebackobj) |
| 446 | |
| 447 | .. XXX document exception chaining |
| 448 | |
| 449 | The "from" clause is used for exception chaining, which is not documented yet. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 450 | |
| 451 | Additional information on exceptions can be found in section :ref:`exceptions`, |
| 452 | and information about handling exceptions is in section :ref:`try`. |
| 453 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 454 | .. seealso:: |
| 455 | |
| 456 | :pep:`3109` - Raising exceptions in Python 3000 |
| 457 | Describes the differences in :keyword:`raise` statements between Python |
| 458 | 2.x and 3.0. |
| 459 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 460 | |
| 461 | .. _break: |
| 462 | |
| 463 | The :keyword:`break` statement |
| 464 | ============================== |
| 465 | |
| 466 | .. index:: statement: break |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 467 | statement: for |
| 468 | statement: while |
| 469 | pair: loop; statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 470 | |
| 471 | .. productionlist:: |
| 472 | break_stmt: "break" |
| 473 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 474 | :keyword:`break` may only occur syntactically nested in a :keyword:`for` or |
| 475 | :keyword:`while` loop, but not nested in a function or class definition within |
| 476 | that loop. |
| 477 | |
| 478 | .. index:: keyword: else |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 479 | pair: loop control; target |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 480 | |
| 481 | It terminates the nearest enclosing loop, skipping the optional :keyword:`else` |
| 482 | clause if the loop has one. |
| 483 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 484 | If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control |
| 485 | target keeps its current value. |
| 486 | |
| 487 | .. index:: keyword: finally |
| 488 | |
| 489 | When :keyword:`break` passes control out of a :keyword:`try` statement with a |
| 490 | :keyword:`finally` clause, that :keyword:`finally` clause is executed before |
| 491 | really leaving the loop. |
| 492 | |
| 493 | |
| 494 | .. _continue: |
| 495 | |
| 496 | The :keyword:`continue` statement |
| 497 | ================================= |
| 498 | |
| 499 | .. index:: statement: continue |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 500 | statement: for |
| 501 | statement: while |
| 502 | pair: loop; statement |
| 503 | keyword: finally |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 504 | |
| 505 | .. productionlist:: |
| 506 | continue_stmt: "continue" |
| 507 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 508 | :keyword:`continue` may only occur syntactically nested in a :keyword:`for` or |
| 509 | :keyword:`while` loop, but not nested in a function or class definition or |
| 510 | :keyword:`finally` statement within that loop. [#]_ It continues with the next |
| 511 | cycle of the nearest enclosing loop. |
| 512 | |
| 513 | |
| 514 | .. _import: |
| 515 | |
| 516 | The :keyword:`import` statement |
| 517 | =============================== |
| 518 | |
| 519 | .. index:: |
| 520 | statement: import |
| 521 | single: module; importing |
| 522 | pair: name; binding |
| 523 | keyword: from |
| 524 | |
| 525 | .. productionlist:: |
| 526 | import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )* |
| 527 | : | "from" `relative_module` "import" `identifier` ["as" `name`] |
| 528 | : ( "," `identifier` ["as" `name`] )* |
| 529 | : | "from" `relative_module` "import" "(" `identifier` ["as" `name`] |
| 530 | : ( "," `identifier` ["as" `name`] )* [","] ")" |
| 531 | : | "from" `module` "import" "*" |
| 532 | module: (`identifier` ".")* `identifier` |
| 533 | relative_module: "."* `module` | "."+ |
| 534 | name: `identifier` |
| 535 | |
| 536 | Import statements are executed in two steps: (1) find a module, and initialize |
| 537 | it if necessary; (2) define a name or names in the local namespace (of the scope |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 538 | where the :keyword:`import` statement occurs). The first form (without |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 539 | :keyword:`from`) repeats these steps for each identifier in the list. The form |
| 540 | with :keyword:`from` performs step (1) once, and then performs step (2) |
| 541 | repeatedly. |
| 542 | |
| 543 | In this context, to "initialize" a built-in or extension module means to call an |
| 544 | initialization function that the module must provide for the purpose (in the |
| 545 | reference implementation, the function's name is obtained by prepending string |
| 546 | "init" to the module's name); to "initialize" a Python-coded module means to |
| 547 | execute the module's body. |
| 548 | |
| 549 | .. index:: |
| 550 | single: modules (in module sys) |
| 551 | single: sys.modules |
| 552 | pair: module; name |
| 553 | pair: built-in; module |
| 554 | pair: user-defined; module |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 555 | pair: filename; extension |
| 556 | triple: module; search; path |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 557 | module: sys |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 558 | |
| 559 | The system maintains a table of modules that have been or are being initialized, |
| 560 | indexed by module name. This table is accessible as ``sys.modules``. When a |
| 561 | module name is found in this table, step (1) is finished. If not, a search for |
| 562 | a module definition is started. When a module is found, it is loaded. Details |
| 563 | of the module searching and loading process are implementation and platform |
| 564 | specific. It generally involves searching for a "built-in" module with the |
| 565 | given name and then searching a list of locations given as ``sys.path``. |
| 566 | |
| 567 | .. index:: |
| 568 | pair: module; initialization |
| 569 | exception: ImportError |
| 570 | single: code block |
| 571 | exception: SyntaxError |
| 572 | |
| 573 | If a built-in module is found, its built-in initialization code is executed and |
| 574 | step (1) is finished. If no matching file is found, :exc:`ImportError` is |
| 575 | raised. If a file is found, it is parsed, yielding an executable code block. If |
| 576 | a syntax error occurs, :exc:`SyntaxError` is raised. Otherwise, an empty module |
| 577 | of the given name is created and inserted in the module table, and then the code |
| 578 | block is executed in the context of this module. Exceptions during this |
| 579 | execution terminate step (1). |
| 580 | |
| 581 | When step (1) finishes without raising an exception, step (2) can begin. |
| 582 | |
| 583 | The first form of :keyword:`import` statement binds the module name in the local |
| 584 | namespace to the module object, and then goes on to import the next identifier, |
| 585 | if any. If the module name is followed by :keyword:`as`, the name following |
| 586 | :keyword:`as` is used as the local name for the module. |
| 587 | |
| 588 | .. index:: |
| 589 | pair: name; binding |
| 590 | exception: ImportError |
| 591 | |
| 592 | The :keyword:`from` form does not bind the module name: it goes through the list |
| 593 | of identifiers, looks each one of them up in the module found in step (1), and |
| 594 | binds the name in the local namespace to the object thus found. As with the |
| 595 | first form of :keyword:`import`, an alternate local name can be supplied by |
| 596 | specifying ":keyword:`as` localname". If a name is not found, |
| 597 | :exc:`ImportError` is raised. If the list of identifiers is replaced by a star |
| 598 | (``'*'``), all public names defined in the module are bound in the local |
| 599 | namespace of the :keyword:`import` statement.. |
| 600 | |
| 601 | .. index:: single: __all__ (optional module attribute) |
| 602 | |
| 603 | The *public names* defined by a module are determined by checking the module's |
| 604 | namespace for a variable named ``__all__``; if defined, it must be a sequence of |
| 605 | strings which are names defined or imported by that module. The names given in |
| 606 | ``__all__`` are all considered public and are required to exist. If ``__all__`` |
| 607 | is not defined, the set of public names includes all names found in the module's |
| 608 | namespace which do not begin with an underscore character (``'_'``). |
| 609 | ``__all__`` should contain the entire public API. It is intended to avoid |
| 610 | accidentally exporting items that are not part of the API (such as library |
| 611 | modules which were imported and used within the module). |
| 612 | |
| 613 | The :keyword:`from` form with ``*`` may only occur in a module scope. If the |
| 614 | wild card form of import --- ``import *`` --- is used in a function and the |
| 615 | function contains or is a nested block with free variables, the compiler will |
| 616 | raise a :exc:`SyntaxError`. |
| 617 | |
| 618 | .. index:: |
| 619 | keyword: from |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 620 | triple: hierarchical; module; names |
| 621 | single: packages |
| 622 | single: __init__.py |
| 623 | |
| 624 | **Hierarchical module names:** when the module names contains one or more dots, |
| 625 | the module search path is carried out differently. The sequence of identifiers |
| 626 | up to the last dot is used to find a "package"; the final identifier is then |
| 627 | searched inside the package. A package is generally a subdirectory of a |
| 628 | directory on ``sys.path`` that has a file :file:`__init__.py`. [XXX Can't be |
| 629 | bothered to spell this out right now; see the URL |
| 630 | http://www.python.org/doc/essays/packages.html for more details, also about how |
| 631 | the module search works from inside a package.] |
| 632 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 633 | .. index:: builtin: __import__ |
| 634 | |
| 635 | The built-in function :func:`__import__` is provided to support applications |
| 636 | that determine which modules need to be loaded dynamically; refer to |
| 637 | :ref:`built-in-funcs` for additional information. |
| 638 | |
| 639 | |
| 640 | .. _future: |
| 641 | |
| 642 | Future statements |
| 643 | ----------------- |
| 644 | |
| 645 | .. index:: pair: future; statement |
| 646 | |
| 647 | A :dfn:`future statement` is a directive to the compiler that a particular |
| 648 | module should be compiled using syntax or semantics that will be available in a |
| 649 | specified future release of Python. The future statement is intended to ease |
| 650 | migration to future versions of Python that introduce incompatible changes to |
| 651 | the language. It allows use of the new features on a per-module basis before |
| 652 | the release in which the feature becomes standard. |
| 653 | |
| 654 | .. productionlist:: * |
| 655 | future_statement: "from" "__future__" "import" feature ["as" name] |
| 656 | : ("," feature ["as" name])* |
| 657 | : | "from" "__future__" "import" "(" feature ["as" name] |
| 658 | : ("," feature ["as" name])* [","] ")" |
| 659 | feature: identifier |
| 660 | name: identifier |
| 661 | |
| 662 | A future statement must appear near the top of the module. The only lines that |
| 663 | can appear before a future statement are: |
| 664 | |
| 665 | * the module docstring (if any), |
| 666 | * comments, |
| 667 | * blank lines, and |
| 668 | * other future statements. |
| 669 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 670 | .. XXX change this if future is cleaned out |
| 671 | |
| 672 | The features recognized by Python 3.0 are ``absolute_import``, ``division``, |
| 673 | ``generators``, ``nested_scopes`` and ``with_statement``. They are all |
| 674 | redundant because they are always enabled, and only kept for backwards |
| 675 | compatibility. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 676 | |
| 677 | A future statement is recognized and treated specially at compile time: Changes |
| 678 | to the semantics of core constructs are often implemented by generating |
| 679 | different code. It may even be the case that a new feature introduces new |
| 680 | incompatible syntax (such as a new reserved word), in which case the compiler |
| 681 | may need to parse the module differently. Such decisions cannot be pushed off |
| 682 | until runtime. |
| 683 | |
| 684 | For any given release, the compiler knows which feature names have been defined, |
| 685 | and raises a compile-time error if a future statement contains a feature not |
| 686 | known to it. |
| 687 | |
| 688 | The direct runtime semantics are the same as for any import statement: there is |
| 689 | a standard module :mod:`__future__`, described later, and it will be imported in |
| 690 | the usual way at the time the future statement is executed. |
| 691 | |
| 692 | The interesting runtime semantics depend on the specific feature enabled by the |
| 693 | future statement. |
| 694 | |
| 695 | Note that there is nothing special about the statement:: |
| 696 | |
| 697 | import __future__ [as name] |
| 698 | |
| 699 | That is not a future statement; it's an ordinary import statement with no |
| 700 | special semantics or syntax restrictions. |
| 701 | |
| 702 | Code compiled by calls to the builtin functions :func:`exec` and :func:`compile` |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 703 | that occur in a module :mod:`M` containing a future statement will, by default, |
| 704 | use the new syntax or semantics associated with the future statement. This can |
| 705 | be controlled by optional arguments to :func:`compile` --- see the documentation |
| 706 | of that function for details. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 707 | |
| 708 | A future statement typed at an interactive interpreter prompt will take effect |
| 709 | for the rest of the interpreter session. If an interpreter is started with the |
| 710 | :option:`-i` option, is passed a script name to execute, and the script includes |
| 711 | a future statement, it will be in effect in the interactive session started |
| 712 | after the script is executed. |
| 713 | |
| 714 | |
| 715 | .. _global: |
| 716 | |
| 717 | The :keyword:`global` statement |
| 718 | =============================== |
| 719 | |
| 720 | .. index:: statement: global |
| 721 | |
| 722 | .. productionlist:: |
| 723 | global_stmt: "global" `identifier` ("," `identifier`)* |
| 724 | |
| 725 | .. index:: triple: global; name; binding |
| 726 | |
| 727 | The :keyword:`global` statement is a declaration which holds for the entire |
| 728 | current code block. It means that the listed identifiers are to be interpreted |
| 729 | as globals. It would be impossible to assign to a global variable without |
| 730 | :keyword:`global`, although free variables may refer to globals without being |
| 731 | declared global. |
| 732 | |
| 733 | Names listed in a :keyword:`global` statement must not be used in the same code |
| 734 | block textually preceding that :keyword:`global` statement. |
| 735 | |
| 736 | Names listed in a :keyword:`global` statement must not be defined as formal |
| 737 | parameters or in a :keyword:`for` loop control target, :keyword:`class` |
| 738 | definition, function definition, or :keyword:`import` statement. |
| 739 | |
| 740 | (The current implementation does not enforce the latter two restrictions, but |
| 741 | programs should not abuse this freedom, as future implementations may enforce |
| 742 | them or silently change the meaning of the program.) |
| 743 | |
| 744 | .. index:: |
| 745 | builtin: exec |
| 746 | builtin: eval |
| 747 | builtin: compile |
| 748 | |
| 749 | **Programmer's note:** the :keyword:`global` is a directive to the parser. It |
| 750 | applies only to code parsed at the same time as the :keyword:`global` statement. |
| 751 | In particular, a :keyword:`global` statement contained in a string or code |
| 752 | object supplied to the builtin :func:`exec` function does not affect the code |
| 753 | block *containing* the function call, and code contained in such a string is |
| 754 | unaffected by :keyword:`global` statements in the code containing the function |
| 755 | call. The same applies to the :func:`eval` and :func:`compile` functions. |
| 756 | |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 757 | |
| 758 | .. _nonlocal: |
| 759 | |
| 760 | The :keyword:`nonlocal` statement |
| 761 | ================================= |
| 762 | |
| 763 | .. index:: statement: nonlocal |
| 764 | |
| 765 | .. productionlist:: |
| 766 | nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)* |
| 767 | |
Georg Brandl | c5d98b4 | 2007-12-04 18:11:03 +0000 | [diff] [blame] | 768 | .. XXX add when implemented |
| 769 | : ["=" (`target_list` "=")+ `expression_list`] |
| 770 | : | "nonlocal" `identifier` `augop` `expression_list` |
| 771 | |
| 772 | The :keyword:`nonlocal` statement causes the listed identifiers to refer to |
| 773 | previously bound variables in the nearest enclosing scope. This is important |
| 774 | because the default behavior for binding is to search the local namespace |
| 775 | first. The statement allows encapsulated code to rebind variables outside of |
| 776 | the local scope besides the global (module) scope. |
| 777 | |
| 778 | .. note:: |
| 779 | |
| 780 | The outer scope for :keyword:`nonlocal` statements cannot be the module |
| 781 | scope. |
| 782 | |
| 783 | .. XXX not implemented |
| 784 | The :keyword:`nonlocal` statement may prepend an assignment or augmented |
| 785 | assignment, but not an expression. |
| 786 | |
| 787 | Names listed in a :keyword:`nonlocal` statement, unlike to those listed in a |
| 788 | :keyword:`global` statement, must refer to pre-existing bindings in an |
| 789 | enclosing scope (the scope in which a new binding should be created cannot |
| 790 | be determined unambiguously). |
| 791 | |
| 792 | Names listed in a :keyword:`nonlocal` statement must not collide with |
| 793 | pre-existing bindings in the local scope. |
| 794 | |
| 795 | .. seealso:: |
| 796 | |
| 797 | :pep:`3104` - Access to Names in Outer Scopes |
| 798 | The specification for the :keyword:`nonlocal` statement. |
Georg Brandl | 02c3056 | 2007-09-07 17:52:53 +0000 | [diff] [blame] | 799 | |
| 800 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 801 | .. rubric:: Footnotes |
| 802 | |
| 803 | .. [#] It may occur within an :keyword:`except` or :keyword:`else` clause. The |
Georg Brandl | c5d98b4 | 2007-12-04 18:11:03 +0000 | [diff] [blame] | 804 | restriction on occurring in the :keyword:`try` clause is implementor's |
| 805 | laziness and will eventually be lifted. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 806 | |