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