rest25/reference/simple_stmts.rst => rest262/reference/simple_stmts.rst
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`
n16-              : \| `assert_stmt`
n16+              : | `assert_stmt`
17-              : \| `assignment_stmt`
17+              : | `assignment_stmt`
18-              : \| `augmented_assignment_stmt`
18+              : | `augmented_assignment_stmt`
19-              : \| `pass_stmt`
19+              : | `pass_stmt`
20-              : \| `del_stmt`
20+              : | `del_stmt`
21-              : \| `print_stmt`
21+              : | `print_stmt`
22-              : \| `return_stmt`
22+              : | `return_stmt`
23-              : \| `yield_stmt`
23+              : | `yield_stmt`
24-              : \| `raise_stmt`
24+              : | `raise_stmt`
25-              : \| `break_stmt`
25+              : | `break_stmt`
26-              : \| `continue_stmt`
26+              : | `continue_stmt`
27-              : \| `import_stmt`
27+              : | `import_stmt`
28-              : \| `global_stmt`
28+              : | `global_stmt`
29-              : \| `exec_stmt`
29+              : | `exec_stmt`
30
31
32.. _exprstmts:
33
34Expression statements
35=====================
36
n37+.. index::
37-.. index:: pair: expression; statement
38+   pair: expression; statement
39+   pair: expression; list
38
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`
n47- 
48-.. index:: pair: expression; list
49
50An expression statement evaluates the expression list (which may be a single
51expression).
52
53.. index::
54   builtin: repr
55   object: None
56   pair: string; conversion
61
62In interactive mode, if the value is not ``None``, it is converted to a string
63using the built-in :func:`repr` function and the resulting string is written to
64standard output (see section :ref:`print`) on a line by itself.  (Expression
65statements yielding ``None`` are not written, so that procedure calls do not
66cause any output.)
67
68
n69-.. _assert:
70- 
71-Assert statements
72-=================
73- 
74-.. index::
75-   statement: assert
76-   pair: debugging; assertions
77- 
78-Assert statements are a convenient way to insert debugging assertions into a
79-program:
80- 
81-.. productionlist::
82-   assert_stmt: "assert" `expression` ["," `expression`]
83- 
84-The simple form, ``assert expression``, is equivalent to ::
85- 
86-   if __debug__:
87-      if not expression: raise AssertionError
88- 
89-The extended form, ``assert expression1, expression2``, is equivalent to ::
90- 
91-   if __debug__:
92-      if not expression1: raise AssertionError, expression2
93- 
94-.. index::
95-   single: __debug__
96-   exception: AssertionError
97- 
98-These equivalences assume that ``__debug__`` and :exc:`AssertionError` refer to
99-the built-in variables with those names.  In the current implementation, the
100-built-in variable ``__debug__`` is ``True`` under normal circumstances,
101-``False`` when optimization is requested (command line option -O).  The current
102-code generator emits no code for an assert statement when optimization is
103-requested at compile time.  Note that it is unnecessary to include the source
104-code for the expression that failed in the error message; it will be displayed
105-as part of the stack trace.
106- 
107-Assignments to ``__debug__`` are illegal.  The value for the built-in variable
108-is determined when the interpreter starts.
109- 
110- 
111.. _assignment:
112
113Assignment statements
114=====================
115
116.. index::
117   pair: assignment; statement
118   pair: binding; name
119   pair: rebinding; name
120   object: mutable
121   pair: attribute; assignment
122
123Assignment statements are used to (re)bind names to values and to modify
124attributes or items of mutable objects:
125
126.. productionlist::
n127-   assignment_stmt: (`target_list` "=")+ `expression_list`
n85+   assignment_stmt: (`target_list` "=")+ (`expression_list` | `yield_expression`)
128-   target_list: `target` ("," `target`)\* [","]
86+   target_list: `target` ("," `target`)* [","]
129   target: `identifier`
n130-         : \| "(" `target_list` ")"
n88+         : | "(" `target_list` ")"
131-         : \| "[" `target_list` "]"
89+         : | "[" `target_list` "]"
132-         : \| `attributeref`
90+         : | `attributeref`
133-         : \| `subscription`
91+         : | `subscription`
134-         : \| `slicing`
92+         : | `slicing`
135
136(See section :ref:`primaries` for the syntax definitions for the last three
137symbols.)
138
139.. index:: pair: expression; list
140
141An assignment statement evaluates the expression list (remember that this can be
142a single expression or a comma-separated list, the latter yielding a tuple) and
155given with the definition of the object types (see section :ref:`types`).
156
157.. index:: triple: target; list; assignment
158
159Assignment of an object to a target list is recursively defined as follows.
160
161* If the target list is a single target: The object is assigned to that target.
162
n163-* If the target list is a comma-separated list of targets: The object must be a
n121+* If the target list is a comma-separated list of targets: The object must be an
164-  sequence with the same number of items as there are targets in the target list,
122+  iterable with the same number of items as there are targets in the target list,
165  and the items are assigned, from left to right, to the corresponding targets.
166  (This rule is relaxed as of Python 1.5; in earlier versions, the object had to
167  be a tuple.  Since strings are sequences, an assignment like ``a, b = "xy"`` is
168  now legal as long as the string has the right length.)
169
170Assignment of an object to a single target is recursively defined as follows.
171
172* If the target is an identifier (name):
173
174    .. index:: statement: global
175
n176-* If the name does not occur in a :keyword:`global` statement in the current
n134+  * If the name does not occur in a :keyword:`global` statement in the current
177    code block: the name is bound to the object in the current local namespace.
178
n179-* Otherwise: the name is bound to the object in the current global namespace.
n137+  * Otherwise: the name is bound to the object in the current global namespace.
180
181  .. index:: single: destructor
182
183  The name is rebound if it was already bound.  This may cause the reference count
184  for the object previously bound to the name to reach zero, causing the object to
185  be deallocated and its destructor (if it has one) to be called.
186
n187-  .. % nested
188- 
189* If the target is a target list enclosed in parentheses or in square brackets:
n190-  The object must be a sequence with the same number of items as there are targets
n146+  The object must be an iterable with the same number of items as there are
191-  in the target list, and its items are assigned, from left to right, to the
147+  targets in the target list, and its items are assigned, from left to right,
192-  corresponding targets.
148+  to the corresponding targets.
193
194  .. index:: pair: attribute; assignment
195
196* If the target is an attribute reference: The primary expression in the
197  reference is evaluated.  It should yield an object with assignable attributes;
198  if this is not the case, :exc:`TypeError` is raised.  That object is then asked
199  to assign the assigned object to the given attribute; if it cannot perform the
200  assignment, it raises an exception (usually but not necessarily
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::
n275-   augmented_assignment_stmt: `target` `augop` `expression_list`
n231+   augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
232+   augtarget: `identifier` | `attributeref` | `subscription` | `slicing`
276-   augop: "+=" \| "-=" \| "\*=" \| "/=" \| "%=" \| "\*\*="
233+   augop: "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="
277-        : \| ">>=" \| "<<=" \| "&=" \| "^=" \| "\|="
234+        : | ">>=" | "<<=" | "&=" | "^=" | "|="
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.
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
n268+.. _assert:
269+ 
270+The :keyword:`assert` statement
271+===============================
272+ 
273+.. index::
274+   statement: assert
275+   pair: debugging; assertions
276+ 
277+Assert statements are a convenient way to insert debugging assertions into a
278+program:
279+ 
280+.. productionlist::
281+   assert_stmt: "assert" `expression` ["," `expression`]
282+ 
283+The simple form, ``assert expression``, is equivalent to ::
284+ 
285+   if __debug__:
286+      if not expression: raise AssertionError
287+ 
288+The extended form, ``assert expression1, expression2``, is equivalent to ::
289+ 
290+   if __debug__:
291+      if not expression1: raise AssertionError, expression2
292+ 
293+.. index::
294+   single: __debug__
295+   exception: AssertionError
296+ 
297+These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
298+the built-in variables with those names.  In the current implementation, the
299+built-in variable :const:`__debug__` is ``True`` under normal circumstances,
300+``False`` when optimization is requested (command line option -O).  The current
301+code generator emits no code for an assert statement when optimization is
302+requested at compile time.  Note that it is unnecessary to include the source
303+code for the expression that failed in the error message; it will be displayed
304+as part of the stack trace.
305+ 
306+Assignments to :const:`__debug__` are illegal.  The value for the built-in variable
307+is determined when the interpreter starts.
308+ 
309+ 
311.. _pass:
312
313The :keyword:`pass` statement
314=============================
315
n316-.. index:: statement: pass
n315+.. index::
316+   statement: pass
317+   pair: null; operation
317
318.. productionlist::
319   pass_stmt: "pass"
n320- 
321-.. index:: pair: null; operation
322
323: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
n337-.. index:: statement: del
338- 
339-.. productionlist::
340-   del_stmt: "del" `target_list`
341- 
342.. index::
n337+   statement: del
343   pair: deletion; target
344   triple: deletion; target; list
n340+ 
341+.. productionlist::
342+   del_stmt: "del" `target_list`
345
346Deletion is recursively defined very similar to the way assignment is defined.
347Rather that spelling it out in full details, here are some hints.
348
349Deletion of a target list recursively deletes each target, from left to right.
350
351.. index::
352   statement: global
373.. _print:
374
375The :keyword:`print` statement
376==============================
377
378.. index:: statement: print
379
380.. productionlist::
n381-   print_stmt: "print" ( [`expression` ("," `expression`)\* [","]]
n379+   print_stmt: "print" ([`expression` ("," `expression`)* [","]]
382-             : \| ">>" `expression` [("," `expression`)+ [","]] )
380+             : | ">>" `expression` [("," `expression`)+ [","]])
383
384:keyword:`print` evaluates each expression in turn and writes the resulting
385object to standard output (see below).  If an object is not a string, it is
386first converted to a string using the rules for string conversions.  The
387(resulting or original) string is then written.  A space is written before each
388object is (converted and) written, unless the output system believes it is
389positioned at the beginning of a line.  This is the case (1) when no characters
390have yet been written to standard output, (2) when the last character written to
396
397   Objects which act like file objects but which are not the built-in file objects
398   often do not properly emulate this aspect of the file object's behavior, so it
399   is best not to rely on this.
400
401.. index::
402   single: output
403   pair: writing; values
n404- 
405-.. index::
406   pair: trailing; comma
407   pair: newline; suppression
408
409A ``'\n'`` character is written at the end, unless the :keyword:`print`
410statement ends with a comma.  This is the only action if the statement contains
411just the keyword :keyword:`print`.
412
413.. index::
431then ``sys.stdout`` is used as the file for output.
432
433
434.. _return:
435
436The :keyword:`return` statement
437===============================
438
n435+.. index::
439-.. index:: statement: return
436+   statement: return
440- 
441-.. productionlist::
442-   return_stmt: "return" [`expression_list`]
443- 
444-.. index::
445   pair: function; definition
446   pair: class; definition
n439+ 
440+.. productionlist::
441+   return_stmt: "return" [`expression_list`]
447
448:keyword:`return` may only occur syntactically nested in a function definition,
449not within a nested class definition.
450
451If an expression list is present, it is evaluated, else ``None`` is substituted.
452
453:keyword:`return` leaves the current function call with the expression list (or
454``None``) as return value.
465raised.
466
467
468.. _yield:
469
470The :keyword:`yield` statement
471==============================
472
n473-.. index:: statement: yield
474- 
475-.. productionlist::
476-   yield_stmt: "yield" `expression_list`
477- 
478.. index::
n469+   statement: yield
479   single: generator; function
480   single: generator; iterator
481   single: function; generator
482   exception: StopIteration
n474+ 
475+.. productionlist::
476+   yield_stmt: `yield_expression`
483
484The :keyword:`yield` statement is only used when defining a generator function,
485and is only used in the body of the generator function. Using a :keyword:`yield`
486statement in a function definition is sufficient to cause that definition to
487create a generator function instead of a normal function.
488
489When a generator function is called, it returns an iterator known as a generator
490iterator, or more commonly, a generator.  The body of the generator function is
503:keyword:`try` clause of a :keyword:`try` ...  :keyword:`finally` construct.  If
504the generator is not resumed before it is finalized (by reaching a zero
505reference count or by being garbage collected), the generator-iterator's
506:meth:`close` method will be called, allowing any pending :keyword:`finally`
507clauses to execute.
508
509.. note::
510
n511-   In Python 2.2, the :keyword:`yield` statement is only allowed when the
n505+   In Python 2.2, the :keyword:`yield` statement was only allowed when the
512-   ``generators`` feature has been enabled.  It will always be enabled in Python
506+   ``generators`` feature has been enabled.  This ``__future__``
513-   2.3.  This ``__future__`` import statement can be used to enable the feature::
507+   import statement was used to enable the feature::
514
515      from __future__ import generators
516
517
518.. seealso::
519
520   :pep:`0255` - Simple Generators
521      The proposal for adding generators and the :keyword:`yield` statement to Python.
525      :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block.
526
527
528.. _raise:
529
530The :keyword:`raise` statement
531==============================
532
n533-.. index:: statement: raise
534- 
535-.. productionlist::
536-   raise_stmt: "raise" [`expression` ["," `expression` ["," `expression`]]]
537- 
538.. index::
n528+   statement: raise
539   single: exception
540   pair: raising; exception
n531+ 
532+.. productionlist::
533+   raise_stmt: "raise" [`expression` ["," `expression` ["," `expression`]]]
541
542If no expressions are present, :keyword:`raise` re-raises the last exception
543that was active in the current scope.  If no exception is active in the current
544scope, a :exc:`TypeError` exception is raised indicating that this is an error
545(if running under IDLE, a :exc:`Queue.Empty` exception is raised instead).
546
547Otherwise, :keyword:`raise` evaluates the expressions to get three objects,
548using ``None`` as the value of omitted expressions.  The first two objects are
558tuple, it is used as the argument list for the class constructor; if it is
559``None``, an empty argument list is used, and any other object is treated as a
560single argument to the constructor.  The instance so created by calling the
561constructor is used as the exception value.
562
563.. index:: object: traceback
564
565If a third object is present and not ``None``, it must be a traceback object
n566-(see section :ref:`traceback`), and it is substituted instead of the current
n559+(see section :ref:`types`), and it is substituted instead of the current
567location as the place where the exception occurred.  If the third object is
568present and not a traceback object or ``None``, a :exc:`TypeError` exception is
569raised.  The three-expression form of :keyword:`raise` is useful to re-raise an
570exception transparently in an except clause, but :keyword:`raise` with no
571expressions should be preferred if the exception to be re-raised was the most
572recently active exception in the current scope.
573
574Additional information on exceptions can be found in section :ref:`exceptions`,
575and information about handling exceptions is in section :ref:`try`.
576
577
578.. _break:
579
580The :keyword:`break` statement
581==============================
582
n583-.. index:: statement: break
584- 
585-.. productionlist::
586-   break_stmt: "break"
587- 
588.. index::
n577+   statement: break
589   statement: for
590   statement: while
591   pair: loop; statement
592
n582+.. productionlist::
583+   break_stmt: "break"
584+ 
593:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
594:keyword:`while` loop, but not nested in a function or class definition within
595that loop.
596
597.. index:: keyword: else
598
599It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
600clause if the loop has one.
611really leaving the loop.
612
613
614.. _continue:
615
616The :keyword:`continue` statement
617=================================
618
n611+.. index::
619-.. index:: statement: continue
612+   statement: continue
620- 
621-.. productionlist::
622-   continue_stmt: "continue"
623- 
624-.. index::
625   statement: for
626   statement: while
627   pair: loop; statement
628   keyword: finally
629
n618+.. productionlist::
619+   continue_stmt: "continue"
620+ 
630:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
631:keyword:`while` loop, but not nested in a function or class definition or
n632-:keyword:`finally` statement within that loop. [#]_ It continues with the next
n623+:keyword:`finally` clause within that loop.  It continues with the next
633cycle of the nearest enclosing loop.
634
n626+When :keyword:`continue` passes control out of a :keyword:`try` statement with a
627+:keyword:`finally` clause, that :keyword:`finally` clause is executed before
628+really starting the next loop cycle.
629+ 
635
636.. _import:
n632+.. _from:
637
638The :keyword:`import` statement
639===============================
640
641.. index::
642   statement: import
643   single: module; importing
644   pair: name; binding
645   keyword: from
646
647.. productionlist::
n648-   import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )\*
n644+   import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )*
649-              : \| "from" `module` "import" `identifier` ["as" `name`]
645+              : | "from" `relative_module` "import" `identifier` ["as" `name`]
650-              : ( "," `identifier` ["as" `name`] )\*
646+              : ( "," `identifier` ["as" `name`] )*
651-              : \| "from" `module` "import" "(" `identifier` ["as" `name`]
647+              : | "from" `relative_module` "import" "(" `identifier` ["as" `name`]
652-              : ( "," `identifier` ["as" `name`] )\* [","] ")"
648+              : ( "," `identifier` ["as" `name`] )* [","] ")"
653-              : \| "from" `module` "import" "\*"
649+              : | "from" `module` "import" "*"
654-   module: (`identifier` ".")\* `identifier`
650+   module: (`identifier` ".")* `identifier`
651+   relative_module: "."* `module` | "."+
652+   name: `identifier`
655
656Import statements are executed in two steps: (1) find a module, and initialize
657it if necessary; (2) define a name or names in the local namespace (of the scope
n658-where the :keyword:`import` statement occurs). The first form (without
n656+where the :keyword:`import` statement occurs). The statement comes in two
657+forms differing on whether it uses the :keyword:`from` keyword. The first form
659-:keyword:`from`) repeats these steps for each identifier in the list.  The form
658+(without :keyword:`from`) repeats these steps for each identifier in the list.
660-with :keyword:`from` performs step (1) once, and then performs step (2)
659+The form with :keyword:`from` performs step (1) once, and then performs step
661-repeatedly.
660+(2) repeatedly.
662
n663-In this context, to "initialize" a built-in or extension module means to call an
664-initialization function that the module must provide for the purpose (in the
665-reference implementation, the function's name is obtained by prepending string
666-"init" to the module's name); to "initialize" a Python-coded module means to
667-execute the module's body.
668- 
669.. index::
n670-   single: modules (in module sys)
n663+    single: package
664+ 
665+To understand how step (1) occurs, one must first understand how Python handles
666+hierarchical naming of modules. To help organize modules and provide a
667+hierarchy in naming, Python has a concept of packages. A package can contain
668+other packages and modules while modules cannot contain other modules or
669+packages. From a file system perspective, packages are directories and modules
670+are files. The original `specification for packages
671+<http://www.python.org/doc/essays/packages.html>`_ is still available to read,
672+although minor details have changed since the writing of that document.
673+ 
674+.. index::
671-   single: sys.modules
675+    single: sys.modules
672-   pair: module; name
673-   pair: built-in; module
674-   pair: user-defined; module
675-   module: sys
676-   pair: filename; extension
677-   triple: module; search; path
678
n679-The system maintains a table of modules that have been or are being initialized,
n677+Once the name of the module is known (unless otherwise specified, the term
680-indexed by module name.  This table is accessible as ``sys.modules``.  When a
678+"module" will refer to both packages and modules), searching
681-module name is found in this table, step (1) is finished.  If not, a search for
679+for the module or package can begin. The first place checked is
682-a module definition is started.  When a module is found, it is loaded.  Details
680+:data:`sys.modules`, the cache of all modules that have been imported
683-of the module searching and loading process are implementation and platform
681+previously. If the module is found there then it is used in step (2) of import.
684-specific.  It generally involves searching for a "built-in" module with the
685-given name and then searching a list of locations given as ``sys.path``.
686
687.. index::
n688-   pair: module; initialization
n684+    single: sys.meta_path
685+    single: finder
686+    pair: finder; find_module
687+    single: __path__
688+ 
689+If the module is not found in the cache, then :data:`sys.meta_path` is searched
690+(the specification for :data:`sys.meta_path` can be found in :pep:`302`).
691+The object is a list of :term:`finder` objects which are queried in order as to
692+whether they know how to load the module by calling their :meth:`find_module`
693+method with the name of the module. If the module happens to be contained
694+within a package (as denoted by the existence of a dot in the name), then a
695+second argument to :meth:`find_module` is given as the value of the
696+:attr:`__path__` attribute from the parent package (everything up to the last
697+dot in the name of the module being imported). If a finder can find the module
698+it returns a :term:`loader` (discussed later) or returns :keyword:`None`.
699+ 
700+.. index::
701+    single: sys.path_hooks
702+    single: sys.path_importer_cache
703+    single: sys.path
704+ 
705+If none of the finders on :data:`sys.meta_path` are able to find the module
706+then some implicitly defined finders are queried. Implementations of Python
707+vary in what implicit meta path finders are defined. The one they all do
708+define, though, is one that handles :data:`sys.path_hooks`,
709+:data:`sys.path_importer_cache`, and :data:`sys.path`.
710+ 
711+The implicit finder searches for the requested module in the "paths" specified
712+in one of two places ("paths" do not have to be file system paths). If the
713+module being imported is supposed to be contained within a package then the
714+second argument passed to :meth:`find_module`, :attr:`__path__` on the parent
715+package, is used as the source of paths. If the module is not contained in a
716+package then :data:`sys.path` is used as the source of paths.
717+ 
718+Once the source of paths is chosen it is iterated over to find a finder that
719+can handle that path. The dict at :data:`sys.path_importer_cache` caches
720+finders for paths and is checked for a finder. If the path does not have a
721+finder cached then :data:`sys.path_hooks` is searched by calling each object in
722+the list with a single argument of the path, returning a finder or raises
723+:exc:`ImportError`. If a finder is returned then it is cached in
724+:data:`sys.path_importer_cache` and then used for that path entry. If no finder
725+can be found but the path exists then a value of :keyword:`None` is
726+stored in :data:`sys.path_importer_cache` to signify that an implicit,
727+file-based finder that handles modules stored as individual files should be
728+used for that path. If the path does not exist then a finder which always
729+returns :keyword:`None` is placed in the cache for the path.
730+ 
731+.. index::
732+    single: loader
733+    pair: loader; load_module
689-   exception: ImportError
734+    exception: ImportError
690-   single: code block
735+ 
736+If no finder can find the module then :exc:`ImportError` is raised. Otherwise
737+some finder returned a loader whose :meth:`load_module` method is called with
738+the name of the module to load (see :pep:`302` for the original definition of
739+loaders). A loader has several responsibilities to perform on a module it
740+loads. First, if the module already exists in :data:`sys.modules` (a
741+possibility if the loader is called outside of the import machinery) then it
742+is to use that module for initialization and not a new module. But if the
743+module does not exist in :data:`sys.modules` then it is to be added to that
744+dict before initialization begins. If an error occurs during loading of the
745+module and it was added to :data:`sys.modules` it is to be removed from the
746+dict. If an error occurs but the module was already in :data:`sys.modules` it
747+is left in the dict.
748+ 
749+.. index::
750+    single: __name__
751+    single: __file__
752+    single: __path__
753+    single: __package__
754+    single: __loader__
755+ 
756+The loader must set several attributes on the module. :data:`__name__` is to be
757+set to the name of the module. :data:`__file__` is to be the "path" to the file
758+unless the module is built-in (and thus listed in
759+:data:`sys.builtin_module_names`) in which case the attribute is not set.
760+If what is being imported is a package then :data:`__path__` is to be set to a
761+list of paths to be searched when looking for modules and packages contained
762+within the package being imported. :data:`__package__` is optional but should
763+be set to the name of package that contains the module or package (the empty
764+string is used for module not contained in a package). :data:`__loader__` is
765+also optional but should be set to the loader object that is loading the
766+module.
767+ 
768+.. index::
691-   exception: SyntaxError
769+    exception: ImportError
692
n693-If a built-in module is found, its built-in initialization code is executed and
n771+If an error occurs during loading then the loader raises :exc:`ImportError` if
694-step (1) is finished.  If no matching file is found, :exc:`ImportError` is
772+some other exception is not already being propagated. Otherwise the loader
695-raised. If a file is found, it is parsed, yielding an executable code block.  If
773+returns the module that was loaded and initialized.
696-a syntax error occurs, :exc:`SyntaxError` is raised.  Otherwise, an empty module
697-of the given name is created and inserted in the module table, and then the code
698-block is executed in the context of this module.  Exceptions during this
699-execution terminate step (1).
700
701When step (1) finishes without raising an exception, step (2) can begin.
702
703The first form of :keyword:`import` statement binds the module name in the local
704namespace to the module object, and then goes on to import the next identifier,
705if any.  If the module name is followed by :keyword:`as`, the name following
706:keyword:`as` is used as the local name for the module.
707
731modules which were imported and used within the module).
732
733The :keyword:`from` form with ``*`` may only occur in a module scope.  If the
734wild card form of import --- ``import *`` --- is used in a function and the
735function contains or is a nested block with free variables, the compiler will
736raise a :exc:`SyntaxError`.
737
738.. index::
n739-   keyword: from
n813+    single: relative; import
740-   statement: from
741
n742-.. index::
n815+When specifying what module to import you do not have to specify the absolute
743-   triple: hierarchical; module; names
816+name of the module. When a module or package is contained within another
744-   single: packages
817+package it is possible to make a relative import within the same top package
745-   single: __init__.py
818+without having to mention the package name. By using leading dots in the
819+specified module or package after :keyword:`from` you can specify how high to
820+traverse up the current package hierarchy without specifying exact names. One
821+leading dot means the current package where the module making the import
822+exists. Two dots means up one package level. Three dots is up two levels, etc.
823+So if you execute ``from . import mod`` from a module in the ``pkg`` package
824+then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
825+imprt mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
826+The specification for relative imports is contained within :pep:`328`.
746
n747-**Hierarchical module names:** when the module names contains one or more dots,
748-the module search path is carried out differently.  The sequence of identifiers
749-up to the last dot is used to find a "package"; the final identifier is then
750-searched inside the package.  A package is generally a subdirectory of a
751-directory on ``sys.path`` that has a file :file:`__init__.py`. [XXX Can't be
752-bothered to spell this out right now; see the URL
753-`<http://www.python.org/doc/essays/packages.html>`_ for more details, also about
754-how the module search works from inside a package.]
755- 
756-.. % 
757
758.. index:: builtin: __import__
759
760The built-in function :func:`__import__` is provided to support applications
n761-that determine which modules need to be loaded dynamically; refer to Built-in
n832+that determine which modules need to be loaded dynamically; refer to
762-Functions (XXX reference: ../lib/built-in-funcs.html) in the Python Library
833+:ref:`built-in-funcs` for additional information.
763-Reference (XXX reference: ../lib/lib.html) for additional information.
764
765
766.. _future:
767
768Future statements
769-----------------
770
771.. index:: pair: future; statement
773A :dfn:`future statement` is a directive to the compiler that a particular
774module should be compiled using syntax or semantics that will be available in a
775specified future release of Python.  The future statement is intended to ease
776migration to future versions of Python that introduce incompatible changes to
777the language.  It allows use of the new features on a per-module basis before
778the release in which the feature becomes standard.
779
780.. productionlist:: *
n781-   future_statement: "from" "__future__" "import" feature ["as" name] ("," feature ["as" name])\*
n851+   future_statement: "from" "__future__" "import" feature ["as" name]
852+                   : ("," feature ["as" name])*
782-                   : \| "from" "__future__" "import" "(" feature ["as" name] ("," feature ["as" name])\* [","] ")"
853+                   : | "from" "__future__" "import" "(" feature ["as" name]
854+                   : ("," feature ["as" name])* [","] ")"
783   feature: identifier
784   name: identifier
785
786A future statement must appear near the top of the module.  The only lines that
787can appear before a future statement are:
788
789* the module docstring (if any),
n790- 
791* comments,
n792- 
793* blank lines, and
n794- 
795* other future statements.
796
n797-The features recognized by Python 2.3 are ``generators``, ``division`` and
n866+The features recognized by Python 2.6 are ``unicode_literals``,
798-``nested_scopes``.  ``generators`` and ``nested_scopes`` are redundant in 2.3
867+``print_function``, ``absolute_import``, ``division``, ``generators``,
799-because they are always enabled.
868+``nested_scopes`` and ``with_statement``.  ``generators``, ``with_statement``,
869+``nested_scopes`` are redundant in Python version 2.6 and above because they are
870+always enabled.
800
801A future statement is recognized and treated specially at compile time: Changes
802to the semantics of core constructs are often implemented by generating
803different code.  It may even be the case that a new feature introduces new
804incompatible syntax (such as a new reserved word), in which case the compiler
805may need to parse the module differently.  Such decisions cannot be pushed off
806until runtime.
807
823That is not a future statement; it's an ordinary import statement with no
824special semantics or syntax restrictions.
825
826Code compiled by an :keyword:`exec` statement or calls to the builtin functions
827:func:`compile` and :func:`execfile` that occur in a module :mod:`M` containing
828a future statement will, by default, use the new  syntax or semantics associated
829with the future statement.  This can, starting with Python 2.2 be controlled by
830optional arguments to :func:`compile` --- see the documentation of that function
n831-in the Python Library Reference (XXX reference: ../lib/built-in-funcs.html) for
832-details.
902+for details.
833
834A future statement typed at an interactive interpreter prompt will take effect
835for the rest of the interpreter session.  If an interpreter is started with the
836:option:`-i` option, is passed a script name to execute, and the script includes
837a future statement, it will be in effect in the interactive session started
838after the script is executed.
839
840
841.. _global:
842
843The :keyword:`global` statement
844===============================
845
n916+.. index::
846-.. index:: statement: global
917+   statement: global
918+   triple: global; name; binding
847
848.. productionlist::
n849-   global_stmt: "global" `identifier` ("," `identifier`)\*
n921+   global_stmt: "global" `identifier` ("," `identifier`)*
850- 
851-.. index:: triple: global; name; binding
852
853The :keyword:`global` statement is a declaration which holds for the entire
854current code block.  It means that the listed identifiers are to be interpreted
855as globals.  It would be impossible to assign to a global variable without
856:keyword:`global`, although free variables may refer to globals without being
857declared global.
858
859Names listed in a :keyword:`global` statement must not be used in the same code
886.. _exec:
887
888The :keyword:`exec` statement
889=============================
890
891.. index:: statement: exec
892
893.. productionlist::
n894-   exec_stmt: "exec" `expression` ["in" `expression` ["," `expression`]]
n964+   exec_stmt: "exec" `or_expr` ["in" `expression` ["," `expression`]]
895
896This statement supports dynamic execution of Python code.  The first expression
897should evaluate to either a string, an open file object, or a code object.  If
898it is a string, the string is parsed as a suite of Python statements which is
n899-then executed (unless a syntax error occurs).  If it is an open file, the file
n969+then executed (unless a syntax error occurs). [#]_  If it is an open file, the file
900is parsed until EOF and executed.  If it is a code object, it is simply
901executed.  In all cases, the code that's executed is expected to be valid as
n902-file input (see section :ref:`file-input`, "File input").  Be aware that the
n972+file input (see section :ref:`file-input`).  Be aware that the
903:keyword:`return` and :keyword:`yield` statements may not be used outside of
904function definitions even within the context of code passed to the
905:keyword:`exec` statement.
906
907In all cases, if the optional parts are omitted, the code is executed in the
908current scope.  If only the first expression after :keyword:`in` is specified,
909it should be a dictionary, which will be used for both the global and the local
910variables.  If two expressions are given, they are used for the global and local
911variables, respectively. If provided, *locals* can be any mapping object.
912
913.. versionchanged:: 2.4
n914-   formerly *locals* was required to be a dictionary.
n984+   Formerly, *locals* was required to be a dictionary.
915
916.. index::
917   single: __builtins__
918   module: __builtin__
919
920As a side effect, an implementation may insert additional keys into the
921dictionaries given besides those corresponding to variable names set by the
922executed code.  For example, the current implementation may add a reference to
928   builtin: globals
929   builtin: locals
930
931**Programmer's hints:** dynamic evaluation of expressions is supported by the
932built-in function :func:`eval`.  The built-in functions :func:`globals` and
933:func:`locals` return the current global and local dictionary, respectively,
934which may be useful to pass around for use by :keyword:`exec`.
935
n1006+ 
936.. rubric:: Footnotes
937
t938-.. [#] It may occur within an :keyword:`except` or :keyword:`else` clause.  The
t1009+.. [#] Note that the parser only accepts the Unix-style end of line convention.
939-   restriction on occurring in the :keyword:`try` clause is implementor's laziness
1010+       If you are reading the code from a file, make sure to use universal
940-   and will eventually be lifted.
1011+       newline mode to convert Windows or Mac-style newlines.
941- 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op