6.12 The import statement

#
6.12 The `import` statement

  import_stmt | ::= | "import" module ["as" name] ( "," module ["as" name] )*
  |  | `| "from" module "import" identifier ["as" name]`
  |  | `( "," identifier ["as" name] )*`
  |  | `| "from" module "import" "(" identifier ["as" name]`
  |  | `( "," identifier ["as" name] )* [","] ")"`
  |  | `| "from" module "import" "*"`
  module | ::= | (identifier ".")* identifier

  Download entire grammar as text.

Import statements are executed in two steps: (1) find a module, andinitialize it if necessary; (2) define a name or names in the localnamespace (of the scope where the `import` statement occurs).The first form (without `from`) repeats these steps for eachidentifier in the list. The form with `from` performs step(1) once, and then performs step (2) repeatedly.

In this context, to ``initialize'' a built-in or extension module means tocall an initialization function that the module must provide for the purpose(in the reference implementation, the function's name is obtained byprepending string ``init'' to the module's name); to ``initialize'' aPython-coded module means to execute the module's body.

The system maintains a table of modules that have been or are beinginitialized,indexed by module name. This table isaccessible as `sys.modules`. When a module name is found inthis table, step (1) is finished. If not, a search for a moduledefinition is started. When a module is found, it is loaded. Detailsof the module searching and loading process are implementation andplatform specific. It generally involves searching for a ``built-in''module with the given name and then searching a list of locationsgiven as `sys.path`.

If a built-in module is found, itsbuilt-in initialization code is executed and step (1) is finished. Ifno matching file is found,`ImportError` is raised.If a file is found, it is parsed,yielding an executable code block. If a syntax error occurs,`SyntaxError` is raised. Otherwise, anempty module of the given name is created and inserted in the moduletable, and then the code block is executed in the context of thismodule. Exceptions during this execution terminate step (1).

When step (1) finishes without raising an exception, step (2) canbegin.

The first form of `import` statement binds the module name inthe local namespace to the module object, and then goes on to importthe next identifier, if any. If the module name is followed by`as`, the name following `as` is used as the localname for the module.

The `from` form does not bind the module name: it goes through thelist of identifiers, looks each one of them up in the module found in step(1), and binds the name in the local namespace to the object thus found. As with the first form of `import`, an alternate local name can besupplied by specifying "`as` localname". If a name is not found,`ImportError` is raised. If the list of identifiers is replacedby a star ("`*`"), all public names defined in the module arebound in the local namespace of the `import` statement..

The public names defined by a module are determined by checkingthe module's namespace for a variable named `__all__`; ifdefined, it must be a sequence of strings which are names defined orimported by that module. The names given in `__all__` are allconsidered public and are required to exist. If `__all__` is notdefined, the set of public names includes all names found in themodule's namespace which do not begin with an underscore character("`_`"). `__all__` should contain the entire public API.It is intended to avoid accidentally exporting items that are not partof the API (such as library modules which were imported and used withinthe module).

The `from` form with "`*`" may only occur in a modulescope. If the wild card form of import -- "`import *`" -- isused in a function and the function contains or is a nested block withfree variables, the compiler will raise a `SyntaxError`.

Hierarchical module names:when the module names contains one or more dots, the module searchpath is carried out differently. The sequence of identifiers up tothe last dot is used to find a ``package''; the finalidentifier is then searched inside the package. A package isgenerally a subdirectory of a directory on `sys.path` that has afile __init__.py.[XXX Can't be bothered to spell this out right now; see the URLhttp://www.python.org/doc/essays/packages.html for more details, alsoabout how the module search works from inside a package.]

The built-in function `__import__()` is provided to supportapplications that determine which modules need to be loadeddynamically; refer to Built-inFunctions in thePython Library Reference for additionalinformation.