Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +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 | : | `print_stmt` |
| 22 | : | `return_stmt` |
| 23 | : | `yield_stmt` |
| 24 | : | `raise_stmt` |
| 25 | : | `break_stmt` |
| 26 | : | `continue_stmt` |
| 27 | : | `import_stmt` |
| 28 | : | `global_stmt` |
| 29 | : | `exec_stmt` |
| 30 | |
| 31 | |
| 32 | .. _exprstmts: |
| 33 | |
| 34 | Expression statements |
| 35 | ===================== |
| 36 | |
| 37 | .. index:: pair: expression; statement |
| 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 | |
| 48 | .. index:: pair: expression; list |
| 49 | |
| 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 |
| 64 | standard output (see section :ref:`print`) on a line by itself. (Expression |
| 65 | statements yielding ``None`` are not written, so that procedure calls do not |
| 66 | cause any output.) |
| 67 | |
| 68 | |
| 69 | .. _assert: |
| 70 | |
| 71 | Assert statements |
| 72 | ================= |
| 73 | |
| 74 | .. index:: |
| 75 | statement: assert |
| 76 | pair: debugging; assertions |
| 77 | |
| 78 | Assert statements are a convenient way to insert debugging assertions into a |
| 79 | program: |
| 80 | |
| 81 | .. productionlist:: |
| 82 | assert_stmt: "assert" `expression` ["," `expression`] |
| 83 | |
| 84 | The simple form, ``assert expression``, is equivalent to :: |
| 85 | |
| 86 | if __debug__: |
| 87 | if not expression: raise AssertionError |
| 88 | |
| 89 | The extended form, ``assert expression1, expression2``, is equivalent to :: |
| 90 | |
| 91 | if __debug__: |
| 92 | if not expression1: raise AssertionError, expression2 |
| 93 | |
| 94 | .. index:: |
| 95 | single: __debug__ |
| 96 | exception: AssertionError |
| 97 | |
| 98 | These equivalences assume that ``__debug__`` and :exc:`AssertionError` refer to |
| 99 | the built-in variables with those names. In the current implementation, the |
| 100 | built-in variable ``__debug__`` is ``True`` under normal circumstances, |
| 101 | ``False`` when optimization is requested (command line option -O). The current |
| 102 | code generator emits no code for an assert statement when optimization is |
| 103 | requested at compile time. Note that it is unnecessary to include the source |
| 104 | code for the expression that failed in the error message; it will be displayed |
| 105 | as part of the stack trace. |
| 106 | |
| 107 | Assignments to ``__debug__`` are illegal. The value for the built-in variable |
| 108 | is determined when the interpreter starts. |
| 109 | |
| 110 | |
| 111 | .. _assignment: |
| 112 | |
| 113 | Assignment statements |
| 114 | ===================== |
| 115 | |
| 116 | .. index:: |
| 117 | pair: assignment; statement |
| 118 | pair: binding; name |
| 119 | pair: rebinding; name |
| 120 | object: mutable |
| 121 | pair: attribute; assignment |
| 122 | |
| 123 | Assignment statements are used to (re)bind names to values and to modify |
| 124 | attributes or items of mutable objects: |
| 125 | |
| 126 | .. productionlist:: |
| 127 | assignment_stmt: (`target_list` "=")+ (`expression_list` | `yield_expression`) |
| 128 | target_list: `target` ("," `target`)* [","] |
| 129 | target: `identifier` |
| 130 | : | "(" `target_list` ")" |
| 131 | : | "[" `target_list` "]" |
| 132 | : | `attributeref` |
| 133 | : | `subscription` |
| 134 | : | `slicing` |
| 135 | |
| 136 | (See section :ref:`primaries` for the syntax definitions for the last three |
| 137 | symbols.) |
| 138 | |
| 139 | .. index:: pair: expression; list |
| 140 | |
| 141 | An assignment statement evaluates the expression list (remember that this can be |
| 142 | a single expression or a comma-separated list, the latter yielding a tuple) and |
| 143 | assigns the single resulting object to each of the target lists, from left to |
| 144 | right. |
| 145 | |
| 146 | .. index:: |
| 147 | single: target |
| 148 | pair: target; list |
| 149 | |
| 150 | Assignment is defined recursively depending on the form of the target (list). |
| 151 | When a target is part of a mutable object (an attribute reference, subscription |
| 152 | or slicing), the mutable object must ultimately perform the assignment and |
| 153 | decide about its validity, and may raise an exception if the assignment is |
| 154 | unacceptable. The rules observed by various types and the exceptions raised are |
| 155 | given with the definition of the object types (see section :ref:`types`). |
| 156 | |
| 157 | .. index:: triple: target; list; assignment |
| 158 | |
| 159 | Assignment of an object to a target list is recursively defined as follows. |
| 160 | |
| 161 | * If the target list is a single target: The object is assigned to that target. |
| 162 | |
| 163 | * If the target list is a comma-separated list of targets: The object must be a |
| 164 | sequence with the same number of items as there are targets in the target list, |
| 165 | and the items are assigned, from left to right, to the corresponding targets. |
| 166 | (This rule is relaxed as of Python 1.5; in earlier versions, the object had to |
| 167 | be a tuple. Since strings are sequences, an assignment like ``a, b = "xy"`` is |
| 168 | now legal as long as the string has the right length.) |
| 169 | |
| 170 | Assignment of an object to a single target is recursively defined as follows. |
| 171 | |
| 172 | * If the target is an identifier (name): |
| 173 | |
| 174 | .. index:: statement: global |
| 175 | |
Georg Brandl | 8360d5d | 2007-09-07 14:14:40 +0000 | [diff] [blame^] | 176 | * If the name does not occur in a :keyword:`global` statement in the current |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 177 | code block: the name is bound to the object in the current local namespace. |
| 178 | |
Georg Brandl | 8360d5d | 2007-09-07 14:14:40 +0000 | [diff] [blame^] | 179 | * Otherwise: the name is bound to the object in the current global namespace. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 180 | |
| 181 | .. index:: single: destructor |
| 182 | |
| 183 | The name is rebound if it was already bound. This may cause the reference count |
| 184 | for the object previously bound to the name to reach zero, causing the object to |
| 185 | be deallocated and its destructor (if it has one) to be called. |
| 186 | |
| 187 | .. % nested |
| 188 | |
| 189 | * If the target is a target list enclosed in parentheses or in square brackets: |
| 190 | The object must be a sequence with the same number of items as there are targets |
| 191 | in the target list, and its items are assigned, from left to right, to the |
| 192 | corresponding targets. |
| 193 | |
| 194 | .. index:: pair: attribute; assignment |
| 195 | |
| 196 | * If the target is an attribute reference: The primary expression in the |
| 197 | reference is evaluated. It should yield an object with assignable attributes; |
| 198 | if this is not the case, :exc:`TypeError` is raised. That object is then asked |
| 199 | to assign the assigned object to the given attribute; if it cannot perform the |
| 200 | assignment, it raises an exception (usually but not necessarily |
| 201 | :exc:`AttributeError`). |
| 202 | |
| 203 | .. index:: |
| 204 | pair: subscription; assignment |
| 205 | object: mutable |
| 206 | |
| 207 | * If the target is a subscription: The primary expression in the reference is |
| 208 | evaluated. It should yield either a mutable sequence object (such as a list) or |
| 209 | a mapping object (such as a dictionary). Next, the subscript expression is |
| 210 | evaluated. |
| 211 | |
| 212 | .. index:: |
| 213 | object: sequence |
| 214 | object: list |
| 215 | |
| 216 | If the primary is a mutable sequence object (such as a list), the subscript must |
| 217 | yield a plain integer. If it is negative, the sequence's length is added to it. |
| 218 | The resulting value must be a nonnegative integer less than the sequence's |
| 219 | length, and the sequence is asked to assign the assigned object to its item with |
| 220 | that index. If the index is out of range, :exc:`IndexError` is raised |
| 221 | (assignment to a subscripted sequence cannot add new items to a list). |
| 222 | |
| 223 | .. index:: |
| 224 | object: mapping |
| 225 | object: dictionary |
| 226 | |
| 227 | If the primary is a mapping object (such as a dictionary), the subscript must |
| 228 | have a type compatible with the mapping's key type, and the mapping is then |
| 229 | asked to create a key/datum pair which maps the subscript to the assigned |
| 230 | object. This can either replace an existing key/value pair with the same key |
| 231 | value, or insert a new key/value pair (if no key with the same value existed). |
| 232 | |
| 233 | .. index:: pair: slicing; assignment |
| 234 | |
| 235 | * If the target is a slicing: The primary expression in the reference is |
| 236 | evaluated. It should yield a mutable sequence object (such as a list). The |
| 237 | assigned object should be a sequence object of the same type. Next, the lower |
| 238 | and upper bound expressions are evaluated, insofar they are present; defaults |
| 239 | are zero and the sequence's length. The bounds should evaluate to (small) |
| 240 | integers. If either bound is negative, the sequence's length is added to it. |
| 241 | The resulting bounds are clipped to lie between zero and the sequence's length, |
| 242 | inclusive. Finally, the sequence object is asked to replace the slice with the |
| 243 | items of the assigned sequence. The length of the slice may be different from |
| 244 | the length of the assigned sequence, thus changing the length of the target |
| 245 | sequence, if the object allows it. |
| 246 | |
| 247 | (In the current implementation, the syntax for targets is taken to be the same |
| 248 | as for expressions, and invalid syntax is rejected during the code generation |
| 249 | phase, causing less detailed error messages.) |
| 250 | |
| 251 | WARNING: Although the definition of assignment implies that overlaps between the |
| 252 | left-hand side and the right-hand side are 'safe' (for example ``a, b = b, a`` |
| 253 | swaps two variables), overlaps *within* the collection of assigned-to variables |
| 254 | are not safe! For instance, the following program prints ``[0, 2]``:: |
| 255 | |
| 256 | x = [0, 1] |
| 257 | i = 0 |
| 258 | i, x[i] = 1, 2 |
| 259 | print x |
| 260 | |
| 261 | |
| 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:: |
| 275 | augmented_assignment_stmt: `target` `augop` (`expression_list` | `yield_expression`) |
| 276 | augop: "+=" | "-=" | "*=" | "/=" | "%=" | "**=" |
| 277 | : | ">>=" | "<<=" | "&=" | "^=" | "|=" |
| 278 | |
| 279 | (See section :ref:`primaries` for the syntax definitions for the last three |
| 280 | symbols.) |
| 281 | |
| 282 | An augmented assignment evaluates the target (which, unlike normal assignment |
| 283 | statements, cannot be an unpacking) and the expression list, performs the binary |
| 284 | operation specific to the type of assignment on the two operands, and assigns |
| 285 | the result to the original target. The target is only evaluated once. |
| 286 | |
| 287 | An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x + |
| 288 | 1`` to achieve a similar, but not exactly equal effect. In the augmented |
| 289 | version, ``x`` is only evaluated once. Also, when possible, the actual operation |
| 290 | is performed *in-place*, meaning that rather than creating a new object and |
| 291 | assigning that to the target, the old object is modified instead. |
| 292 | |
| 293 | With the exception of assigning to tuples and multiple targets in a single |
| 294 | statement, the assignment done by augmented assignment statements is handled the |
| 295 | same way as normal assignments. Similarly, with the exception of the possible |
| 296 | *in-place* behavior, the binary operation performed by augmented assignment is |
| 297 | the same as the normal binary operations. |
| 298 | |
| 299 | For targets which are attribute references, the initial value is retrieved with |
| 300 | a :meth:`getattr` and the result is assigned with a :meth:`setattr`. Notice |
| 301 | that the two methods do not necessarily refer to the same variable. When |
| 302 | :meth:`getattr` refers to a class variable, :meth:`setattr` still writes to an |
| 303 | instance variable. For example:: |
| 304 | |
| 305 | class A: |
| 306 | x = 3 # class variable |
| 307 | a = A() |
| 308 | a.x += 1 # writes a.x as 4 leaving A.x as 3 |
| 309 | |
| 310 | |
| 311 | .. _pass: |
| 312 | |
| 313 | The :keyword:`pass` statement |
| 314 | ============================= |
| 315 | |
| 316 | .. index:: statement: pass |
| 317 | |
| 318 | .. productionlist:: |
| 319 | pass_stmt: "pass" |
| 320 | |
| 321 | .. index:: pair: null; operation |
| 322 | |
| 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 |
| 338 | |
| 339 | .. productionlist:: |
| 340 | del_stmt: "del" `target_list` |
| 341 | |
| 342 | .. index:: |
| 343 | pair: deletion; target |
| 344 | triple: deletion; target; list |
| 345 | |
| 346 | Deletion is recursively defined very similar to the way assignment is defined. |
| 347 | Rather that spelling it out in full details, here are some hints. |
| 348 | |
| 349 | Deletion of a target list recursively deletes each target, from left to right. |
| 350 | |
| 351 | .. index:: |
| 352 | statement: global |
| 353 | pair: unbinding; name |
| 354 | |
| 355 | Deletion of a name removes the binding of that name from the local or global |
| 356 | namespace, depending on whether the name occurs in a :keyword:`global` statement |
| 357 | in the same code block. If the name is unbound, a :exc:`NameError` exception |
| 358 | will be raised. |
| 359 | |
| 360 | .. index:: pair: free; variable |
| 361 | |
| 362 | It is illegal to delete a name from the local namespace if it occurs as a free |
| 363 | variable in a nested block. |
| 364 | |
| 365 | .. index:: pair: attribute; deletion |
| 366 | |
| 367 | Deletion of attribute references, subscriptions and slicings is passed to the |
| 368 | primary object involved; deletion of a slicing is in general equivalent to |
| 369 | assignment of an empty slice of the right type (but even this is determined by |
| 370 | the sliced object). |
| 371 | |
| 372 | |
| 373 | .. _print: |
| 374 | |
| 375 | The :keyword:`print` statement |
| 376 | ============================== |
| 377 | |
| 378 | .. index:: statement: print |
| 379 | |
| 380 | .. productionlist:: |
| 381 | print_stmt: "print" ([`expression` ("," `expression`)* [","] |
| 382 | : | ">>" `expression` [("," `expression`)+ [","]) |
| 383 | |
| 384 | :keyword:`print` evaluates each expression in turn and writes the resulting |
| 385 | object to standard output (see below). If an object is not a string, it is |
| 386 | first converted to a string using the rules for string conversions. The |
| 387 | (resulting or original) string is then written. A space is written before each |
| 388 | object is (converted and) written, unless the output system believes it is |
| 389 | positioned at the beginning of a line. This is the case (1) when no characters |
| 390 | have yet been written to standard output, (2) when the last character written to |
| 391 | standard output is ``'\n'``, or (3) when the last write operation on standard |
| 392 | output was not a :keyword:`print` statement. (In some cases it may be |
| 393 | functional to write an empty string to standard output for this reason.) |
| 394 | |
| 395 | .. note:: |
| 396 | |
| 397 | Objects which act like file objects but which are not the built-in file objects |
| 398 | often do not properly emulate this aspect of the file object's behavior, so it |
| 399 | is best not to rely on this. |
| 400 | |
| 401 | .. index:: |
| 402 | single: output |
| 403 | pair: writing; values |
| 404 | |
| 405 | .. index:: |
| 406 | pair: trailing; comma |
| 407 | pair: newline; suppression |
| 408 | |
| 409 | A ``'\n'`` character is written at the end, unless the :keyword:`print` |
| 410 | statement ends with a comma. This is the only action if the statement contains |
| 411 | just the keyword :keyword:`print`. |
| 412 | |
| 413 | .. index:: |
| 414 | pair: standard; output |
| 415 | module: sys |
| 416 | single: stdout (in module sys) |
| 417 | exception: RuntimeError |
| 418 | |
| 419 | Standard output is defined as the file object named ``stdout`` in the built-in |
| 420 | module :mod:`sys`. If no such object exists, or if it does not have a |
| 421 | :meth:`write` method, a :exc:`RuntimeError` exception is raised. |
| 422 | |
| 423 | .. index:: single: extended print statement |
| 424 | |
| 425 | :keyword:`print` also has an extended form, defined by the second portion of the |
| 426 | syntax described above. This form is sometimes referred to as ":keyword:`print` |
| 427 | chevron." In this form, the first expression after the ``>>`` must evaluate to a |
| 428 | "file-like" object, specifically an object that has a :meth:`write` method as |
| 429 | described above. With this extended form, the subsequent expressions are |
| 430 | printed to this file object. If the first expression evaluates to ``None``, |
| 431 | then ``sys.stdout`` is used as the file for output. |
| 432 | |
| 433 | |
| 434 | .. _return: |
| 435 | |
| 436 | The :keyword:`return` statement |
| 437 | =============================== |
| 438 | |
| 439 | .. index:: statement: return |
| 440 | |
| 441 | .. productionlist:: |
| 442 | return_stmt: "return" [`expression_list`] |
| 443 | |
| 444 | .. index:: |
| 445 | pair: function; definition |
| 446 | pair: class; definition |
| 447 | |
| 448 | :keyword:`return` may only occur syntactically nested in a function definition, |
| 449 | not within a nested class definition. |
| 450 | |
| 451 | If an expression list is present, it is evaluated, else ``None`` is substituted. |
| 452 | |
| 453 | :keyword:`return` leaves the current function call with the expression list (or |
| 454 | ``None``) as return value. |
| 455 | |
| 456 | .. index:: keyword: finally |
| 457 | |
| 458 | When :keyword:`return` passes control out of a :keyword:`try` statement with a |
| 459 | :keyword:`finally` clause, that :keyword:`finally` clause is executed before |
| 460 | really leaving the function. |
| 461 | |
| 462 | In a generator function, the :keyword:`return` statement is not allowed to |
| 463 | include an :token:`expression_list`. In that context, a bare :keyword:`return` |
| 464 | indicates that the generator is done and will cause :exc:`StopIteration` to be |
| 465 | raised. |
| 466 | |
| 467 | |
| 468 | .. _yield: |
| 469 | |
| 470 | The :keyword:`yield` statement |
| 471 | ============================== |
| 472 | |
| 473 | .. index:: statement: yield |
| 474 | |
| 475 | .. productionlist:: |
| 476 | yield_stmt: `yield_expression` |
| 477 | |
| 478 | .. index:: |
| 479 | single: generator; function |
| 480 | single: generator; iterator |
| 481 | single: function; generator |
| 482 | exception: StopIteration |
| 483 | |
| 484 | The :keyword:`yield` statement is only used when defining a generator function, |
| 485 | and is only used in the body of the generator function. Using a :keyword:`yield` |
| 486 | statement in a function definition is sufficient to cause that definition to |
| 487 | create a generator function instead of a normal function. |
| 488 | |
| 489 | When a generator function is called, it returns an iterator known as a generator |
| 490 | iterator, or more commonly, a generator. The body of the generator function is |
| 491 | executed by calling the generator's :meth:`next` method repeatedly until it |
| 492 | raises an exception. |
| 493 | |
| 494 | When a :keyword:`yield` statement is executed, the state of the generator is |
| 495 | frozen and the value of :token:`expression_list` is returned to :meth:`next`'s |
| 496 | caller. By "frozen" we mean that all local state is retained, including the |
| 497 | current bindings of local variables, the instruction pointer, and the internal |
| 498 | evaluation stack: enough information is saved so that the next time :meth:`next` |
| 499 | is invoked, the function can proceed exactly as if the :keyword:`yield` |
| 500 | statement were just another external call. |
| 501 | |
| 502 | As of Python version 2.5, the :keyword:`yield` statement is now allowed in the |
| 503 | :keyword:`try` clause of a :keyword:`try` ... :keyword:`finally` construct. If |
| 504 | the generator is not resumed before it is finalized (by reaching a zero |
| 505 | reference count or by being garbage collected), the generator-iterator's |
| 506 | :meth:`close` method will be called, allowing any pending :keyword:`finally` |
| 507 | clauses to execute. |
| 508 | |
| 509 | .. note:: |
| 510 | |
| 511 | In Python 2.2, the :keyword:`yield` statement is only allowed when the |
| 512 | ``generators`` feature has been enabled. It will always be enabled in Python |
| 513 | 2.3. This ``__future__`` import statement can be used to enable the feature:: |
| 514 | |
| 515 | from __future__ import generators |
| 516 | |
| 517 | |
| 518 | .. seealso:: |
| 519 | |
| 520 | :pep:`0255` - Simple Generators |
| 521 | The proposal for adding generators and the :keyword:`yield` statement to Python. |
| 522 | |
| 523 | :pep:`0342` - Coroutines via Enhanced Generators |
| 524 | The proposal that, among other generator enhancements, proposed allowing |
| 525 | :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block. |
| 526 | |
| 527 | |
| 528 | .. _raise: |
| 529 | |
| 530 | The :keyword:`raise` statement |
| 531 | ============================== |
| 532 | |
| 533 | .. index:: statement: raise |
| 534 | |
| 535 | .. productionlist:: |
| 536 | raise_stmt: "raise" [`expression` ["," `expression` ["," `expression`]]] |
| 537 | |
| 538 | .. index:: |
| 539 | single: exception |
| 540 | pair: raising; exception |
| 541 | |
| 542 | If no expressions are present, :keyword:`raise` re-raises the last exception |
| 543 | that was active in the current scope. If no exception is active in the current |
| 544 | scope, a :exc:`TypeError` exception is raised indicating that this is an error |
| 545 | (if running under IDLE, a :exc:`Queue.Empty` exception is raised instead). |
| 546 | |
| 547 | Otherwise, :keyword:`raise` evaluates the expressions to get three objects, |
| 548 | using ``None`` as the value of omitted expressions. The first two objects are |
| 549 | used to determine the *type* and *value* of the exception. |
| 550 | |
| 551 | If the first object is an instance, the type of the exception is the class of |
| 552 | the instance, the instance itself is the value, and the second object must be |
| 553 | ``None``. |
| 554 | |
| 555 | If the first object is a class, it becomes the type of the exception. The second |
| 556 | object is used to determine the exception value: If it is an instance of the |
| 557 | class, the instance becomes the exception value. If the second object is a |
| 558 | tuple, it is used as the argument list for the class constructor; if it is |
| 559 | ``None``, an empty argument list is used, and any other object is treated as a |
| 560 | single argument to the constructor. The instance so created by calling the |
| 561 | constructor is used as the exception value. |
| 562 | |
| 563 | .. index:: object: traceback |
| 564 | |
| 565 | If a third object is present and not ``None``, it must be a traceback object |
| 566 | (see section :ref:`types`), and it is substituted instead of the current |
| 567 | location as the place where the exception occurred. If the third object is |
| 568 | present and not a traceback object or ``None``, a :exc:`TypeError` exception is |
| 569 | raised. The three-expression form of :keyword:`raise` is useful to re-raise an |
| 570 | exception transparently in an except clause, but :keyword:`raise` with no |
| 571 | expressions should be preferred if the exception to be re-raised was the most |
| 572 | recently active exception in the current scope. |
| 573 | |
| 574 | Additional information on exceptions can be found in section :ref:`exceptions`, |
| 575 | and information about handling exceptions is in section :ref:`try`. |
| 576 | |
| 577 | |
| 578 | .. _break: |
| 579 | |
| 580 | The :keyword:`break` statement |
| 581 | ============================== |
| 582 | |
| 583 | .. index:: statement: break |
| 584 | |
| 585 | .. productionlist:: |
| 586 | break_stmt: "break" |
| 587 | |
| 588 | .. index:: |
| 589 | statement: for |
| 590 | statement: while |
| 591 | pair: loop; statement |
| 592 | |
| 593 | :keyword:`break` may only occur syntactically nested in a :keyword:`for` or |
| 594 | :keyword:`while` loop, but not nested in a function or class definition within |
| 595 | that loop. |
| 596 | |
| 597 | .. index:: keyword: else |
| 598 | |
| 599 | It terminates the nearest enclosing loop, skipping the optional :keyword:`else` |
| 600 | clause if the loop has one. |
| 601 | |
| 602 | .. index:: pair: loop control; target |
| 603 | |
| 604 | If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control |
| 605 | target keeps its current value. |
| 606 | |
| 607 | .. index:: keyword: finally |
| 608 | |
| 609 | When :keyword:`break` passes control out of a :keyword:`try` statement with a |
| 610 | :keyword:`finally` clause, that :keyword:`finally` clause is executed before |
| 611 | really leaving the loop. |
| 612 | |
| 613 | |
| 614 | .. _continue: |
| 615 | |
| 616 | The :keyword:`continue` statement |
| 617 | ================================= |
| 618 | |
| 619 | .. index:: statement: continue |
| 620 | |
| 621 | .. productionlist:: |
| 622 | continue_stmt: "continue" |
| 623 | |
| 624 | .. index:: |
| 625 | statement: for |
| 626 | statement: while |
| 627 | pair: loop; statement |
| 628 | keyword: finally |
| 629 | |
| 630 | :keyword:`continue` may only occur syntactically nested in a :keyword:`for` or |
| 631 | :keyword:`while` loop, but not nested in a function or class definition or |
| 632 | :keyword:`finally` statement within that loop. [#]_ It continues with the next |
| 633 | cycle of the nearest enclosing loop. |
| 634 | |
| 635 | |
| 636 | .. _import: |
| 637 | |
| 638 | The :keyword:`import` statement |
| 639 | =============================== |
| 640 | |
| 641 | .. index:: |
| 642 | statement: import |
| 643 | single: module; importing |
| 644 | pair: name; binding |
| 645 | keyword: from |
| 646 | |
| 647 | .. productionlist:: |
| 648 | import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )* |
| 649 | : | "from" `relative_module` "import" `identifier` ["as" `name`] |
| 650 | : ( "," `identifier` ["as" `name`] )* |
| 651 | : | "from" `relative_module` "import" "(" `identifier` ["as" `name`] |
| 652 | : ( "," `identifier` ["as" `name`] )* [","] ")" |
| 653 | : | "from" `module` "import" "*" |
| 654 | module: (`identifier` ".")* `identifier` |
| 655 | relative_module: "."* `module` | "."+ |
| 656 | name: `identifier` |
| 657 | |
| 658 | Import statements are executed in two steps: (1) find a module, and initialize |
| 659 | it if necessary; (2) define a name or names in the local namespace (of the scope |
| 660 | where the :keyword:`import` statement occurs). The first form (without |
| 661 | :keyword:`from`) repeats these steps for each identifier in the list. The form |
| 662 | with :keyword:`from` performs step (1) once, and then performs step (2) |
| 663 | repeatedly. |
| 664 | |
| 665 | In this context, to "initialize" a built-in or extension module means to call an |
| 666 | initialization function that the module must provide for the purpose (in the |
| 667 | reference implementation, the function's name is obtained by prepending string |
| 668 | "init" to the module's name); to "initialize" a Python-coded module means to |
| 669 | execute the module's body. |
| 670 | |
| 671 | .. index:: |
| 672 | single: modules (in module sys) |
| 673 | single: sys.modules |
| 674 | pair: module; name |
| 675 | pair: built-in; module |
| 676 | pair: user-defined; module |
| 677 | module: sys |
| 678 | pair: filename; extension |
| 679 | triple: module; search; path |
| 680 | |
| 681 | The system maintains a table of modules that have been or are being initialized, |
| 682 | indexed by module name. This table is accessible as ``sys.modules``. When a |
| 683 | module name is found in this table, step (1) is finished. If not, a search for |
| 684 | a module definition is started. When a module is found, it is loaded. Details |
| 685 | of the module searching and loading process are implementation and platform |
| 686 | specific. It generally involves searching for a "built-in" module with the |
| 687 | given name and then searching a list of locations given as ``sys.path``. |
| 688 | |
| 689 | .. index:: |
| 690 | pair: module; initialization |
| 691 | exception: ImportError |
| 692 | single: code block |
| 693 | exception: SyntaxError |
| 694 | |
| 695 | If a built-in module is found, its built-in initialization code is executed and |
| 696 | step (1) is finished. If no matching file is found, :exc:`ImportError` is |
| 697 | raised. If a file is found, it is parsed, yielding an executable code block. If |
| 698 | a syntax error occurs, :exc:`SyntaxError` is raised. Otherwise, an empty module |
| 699 | of the given name is created and inserted in the module table, and then the code |
| 700 | block is executed in the context of this module. Exceptions during this |
| 701 | execution terminate step (1). |
| 702 | |
| 703 | When step (1) finishes without raising an exception, step (2) can begin. |
| 704 | |
| 705 | The first form of :keyword:`import` statement binds the module name in the local |
| 706 | namespace to the module object, and then goes on to import the next identifier, |
| 707 | if any. If the module name is followed by :keyword:`as`, the name following |
| 708 | :keyword:`as` is used as the local name for the module. |
| 709 | |
| 710 | .. index:: |
| 711 | pair: name; binding |
| 712 | exception: ImportError |
| 713 | |
| 714 | The :keyword:`from` form does not bind the module name: it goes through the list |
| 715 | of identifiers, looks each one of them up in the module found in step (1), and |
| 716 | binds the name in the local namespace to the object thus found. As with the |
| 717 | first form of :keyword:`import`, an alternate local name can be supplied by |
| 718 | specifying ":keyword:`as` localname". If a name is not found, |
| 719 | :exc:`ImportError` is raised. If the list of identifiers is replaced by a star |
| 720 | (``'*'``), all public names defined in the module are bound in the local |
| 721 | namespace of the :keyword:`import` statement.. |
| 722 | |
| 723 | .. index:: single: __all__ (optional module attribute) |
| 724 | |
| 725 | The *public names* defined by a module are determined by checking the module's |
| 726 | namespace for a variable named ``__all__``; if defined, it must be a sequence of |
| 727 | strings which are names defined or imported by that module. The names given in |
| 728 | ``__all__`` are all considered public and are required to exist. If ``__all__`` |
| 729 | is not defined, the set of public names includes all names found in the module's |
| 730 | namespace which do not begin with an underscore character (``'_'``). |
| 731 | ``__all__`` should contain the entire public API. It is intended to avoid |
| 732 | accidentally exporting items that are not part of the API (such as library |
| 733 | modules which were imported and used within the module). |
| 734 | |
| 735 | The :keyword:`from` form with ``*`` may only occur in a module scope. If the |
| 736 | wild card form of import --- ``import *`` --- is used in a function and the |
| 737 | function contains or is a nested block with free variables, the compiler will |
| 738 | raise a :exc:`SyntaxError`. |
| 739 | |
| 740 | .. index:: |
| 741 | keyword: from |
| 742 | statement: from |
| 743 | |
| 744 | .. index:: |
| 745 | triple: hierarchical; module; names |
| 746 | single: packages |
| 747 | single: __init__.py |
| 748 | |
| 749 | **Hierarchical module names:** when the module names contains one or more dots, |
| 750 | the module search path is carried out differently. The sequence of identifiers |
| 751 | up to the last dot is used to find a "package"; the final identifier is then |
| 752 | searched inside the package. A package is generally a subdirectory of a |
| 753 | directory on ``sys.path`` that has a file :file:`__init__.py`. [XXX Can't be |
| 754 | bothered to spell this out right now; see the URL |
| 755 | http://www.python.org/doc/essays/packages.html for more details, also about how |
| 756 | the module search works from inside a package.] |
| 757 | |
| 758 | .. % |
| 759 | |
| 760 | .. index:: builtin: __import__ |
| 761 | |
| 762 | The built-in function :func:`__import__` is provided to support applications |
| 763 | that determine which modules need to be loaded dynamically; refer to |
| 764 | :ref:`built-in-funcs` for additional information. |
| 765 | |
| 766 | |
| 767 | .. _future: |
| 768 | |
| 769 | Future statements |
| 770 | ----------------- |
| 771 | |
| 772 | .. index:: pair: future; statement |
| 773 | |
| 774 | A :dfn:`future statement` is a directive to the compiler that a particular |
| 775 | module should be compiled using syntax or semantics that will be available in a |
| 776 | specified future release of Python. The future statement is intended to ease |
| 777 | migration to future versions of Python that introduce incompatible changes to |
| 778 | the language. It allows use of the new features on a per-module basis before |
| 779 | the release in which the feature becomes standard. |
| 780 | |
| 781 | .. productionlist:: * |
| 782 | future_statement: "from" "__future__" "import" feature ["as" name] |
| 783 | : ("," feature ["as" name])* |
| 784 | : | "from" "__future__" "import" "(" feature ["as" name] |
| 785 | : ("," feature ["as" name])* [","] ")" |
| 786 | feature: identifier |
| 787 | name: identifier |
| 788 | |
| 789 | A future statement must appear near the top of the module. The only lines that |
| 790 | can appear before a future statement are: |
| 791 | |
| 792 | * the module docstring (if any), |
| 793 | * comments, |
| 794 | * blank lines, and |
| 795 | * other future statements. |
| 796 | |
| 797 | The features recognized by Python 2.5 are ``absolute_import``, ``division``, |
| 798 | ``generators``, ``nested_scopes`` and ``with_statement``. ``generators`` and |
| 799 | ``nested_scopes`` are redundant in Python version 2.3 and above because they |
| 800 | are always enabled. |
| 801 | |
| 802 | A future statement is recognized and treated specially at compile time: Changes |
| 803 | to the semantics of core constructs are often implemented by generating |
| 804 | different code. It may even be the case that a new feature introduces new |
| 805 | incompatible syntax (such as a new reserved word), in which case the compiler |
| 806 | may need to parse the module differently. Such decisions cannot be pushed off |
| 807 | until runtime. |
| 808 | |
| 809 | For any given release, the compiler knows which feature names have been defined, |
| 810 | and raises a compile-time error if a future statement contains a feature not |
| 811 | known to it. |
| 812 | |
| 813 | The direct runtime semantics are the same as for any import statement: there is |
| 814 | a standard module :mod:`__future__`, described later, and it will be imported in |
| 815 | the usual way at the time the future statement is executed. |
| 816 | |
| 817 | The interesting runtime semantics depend on the specific feature enabled by the |
| 818 | future statement. |
| 819 | |
| 820 | Note that there is nothing special about the statement:: |
| 821 | |
| 822 | import __future__ [as name] |
| 823 | |
| 824 | That is not a future statement; it's an ordinary import statement with no |
| 825 | special semantics or syntax restrictions. |
| 826 | |
| 827 | Code compiled by an :keyword:`exec` statement or calls to the builtin functions |
| 828 | :func:`compile` and :func:`execfile` that occur in a module :mod:`M` containing |
| 829 | a future statement will, by default, use the new syntax or semantics associated |
| 830 | with the future statement. This can, starting with Python 2.2 be controlled by |
| 831 | optional arguments to :func:`compile` --- see the documentation of that function |
| 832 | for details. |
| 833 | |
| 834 | A future statement typed at an interactive interpreter prompt will take effect |
| 835 | for the rest of the interpreter session. If an interpreter is started with the |
| 836 | :option:`-i` option, is passed a script name to execute, and the script includes |
| 837 | a future statement, it will be in effect in the interactive session started |
| 838 | after the script is executed. |
| 839 | |
| 840 | |
| 841 | .. _global: |
| 842 | |
| 843 | The :keyword:`global` statement |
| 844 | =============================== |
| 845 | |
| 846 | .. index:: statement: global |
| 847 | |
| 848 | .. productionlist:: |
| 849 | global_stmt: "global" `identifier` ("," `identifier`)* |
| 850 | |
| 851 | .. index:: triple: global; name; binding |
| 852 | |
| 853 | The :keyword:`global` statement is a declaration which holds for the entire |
| 854 | current code block. It means that the listed identifiers are to be interpreted |
| 855 | as globals. It would be impossible to assign to a global variable without |
| 856 | :keyword:`global`, although free variables may refer to globals without being |
| 857 | declared global. |
| 858 | |
| 859 | Names listed in a :keyword:`global` statement must not be used in the same code |
| 860 | block textually preceding that :keyword:`global` statement. |
| 861 | |
| 862 | Names listed in a :keyword:`global` statement must not be defined as formal |
| 863 | parameters or in a :keyword:`for` loop control target, :keyword:`class` |
| 864 | definition, function definition, or :keyword:`import` statement. |
| 865 | |
| 866 | (The current implementation does not enforce the latter two restrictions, but |
| 867 | programs should not abuse this freedom, as future implementations may enforce |
| 868 | them or silently change the meaning of the program.) |
| 869 | |
| 870 | .. index:: |
| 871 | statement: exec |
| 872 | builtin: eval |
| 873 | builtin: execfile |
| 874 | builtin: compile |
| 875 | |
| 876 | **Programmer's note:** the :keyword:`global` is a directive to the parser. It |
| 877 | applies only to code parsed at the same time as the :keyword:`global` statement. |
| 878 | In particular, a :keyword:`global` statement contained in an :keyword:`exec` |
| 879 | statement does not affect the code block *containing* the :keyword:`exec` |
| 880 | statement, and code contained in an :keyword:`exec` statement is unaffected by |
| 881 | :keyword:`global` statements in the code containing the :keyword:`exec` |
| 882 | statement. The same applies to the :func:`eval`, :func:`execfile` and |
| 883 | :func:`compile` functions. |
| 884 | |
| 885 | |
| 886 | .. _exec: |
| 887 | |
| 888 | The :keyword:`exec` statement |
| 889 | ============================= |
| 890 | |
| 891 | .. index:: statement: exec |
| 892 | |
| 893 | .. productionlist:: |
| 894 | exec_stmt: "exec" `or_expr` ["in" `expression` ["," `expression`]] |
| 895 | |
| 896 | This statement supports dynamic execution of Python code. The first expression |
| 897 | should evaluate to either a string, an open file object, or a code object. If |
| 898 | it is a string, the string is parsed as a suite of Python statements which is |
| 899 | then executed (unless a syntax error occurs). If it is an open file, the file |
| 900 | is parsed until EOF and executed. If it is a code object, it is simply |
| 901 | executed. In all cases, the code that's executed is expected to be valid as |
| 902 | file input (see section :ref:`file-input`). Be aware that the |
| 903 | :keyword:`return` and :keyword:`yield` statements may not be used outside of |
| 904 | function definitions even within the context of code passed to the |
| 905 | :keyword:`exec` statement. |
| 906 | |
| 907 | In all cases, if the optional parts are omitted, the code is executed in the |
| 908 | current scope. If only the first expression after :keyword:`in` is specified, |
| 909 | it should be a dictionary, which will be used for both the global and the local |
| 910 | variables. If two expressions are given, they are used for the global and local |
| 911 | variables, respectively. If provided, *locals* can be any mapping object. |
| 912 | |
| 913 | .. versionchanged:: 2.4 |
| 914 | formerly *locals* was required to be a dictionary. |
| 915 | |
| 916 | .. index:: |
| 917 | single: __builtins__ |
| 918 | module: __builtin__ |
| 919 | |
| 920 | As a side effect, an implementation may insert additional keys into the |
| 921 | dictionaries given besides those corresponding to variable names set by the |
| 922 | executed code. For example, the current implementation may add a reference to |
| 923 | the dictionary of the built-in module :mod:`__builtin__` under the key |
| 924 | ``__builtins__`` (!). |
| 925 | |
| 926 | .. index:: |
| 927 | builtin: eval |
| 928 | builtin: globals |
| 929 | builtin: locals |
| 930 | |
| 931 | **Programmer's hints:** dynamic evaluation of expressions is supported by the |
| 932 | built-in function :func:`eval`. The built-in functions :func:`globals` and |
| 933 | :func:`locals` return the current global and local dictionary, respectively, |
| 934 | which may be useful to pass around for use by :keyword:`exec`. |
| 935 | |
| 936 | .. rubric:: Footnotes |
| 937 | |
| 938 | .. [#] It may occur within an :keyword:`except` or :keyword:`else` clause. The |
| 939 | restriction on occurring in the :keyword:`try` clause is implementor's laziness |
| 940 | and will eventually be lifted. |
| 941 | |