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