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