@@ -642,48 +642,125 @@ The :keyword:`import` statement
642642
643643Import statements are executed in two steps: (1) find a module, and initialize
644644it if necessary; (2) define a name or names in the local namespace (of the scope
645- where the :keyword: `import ` statement occurs). The first form (without
646- :keyword: `from `) repeats these steps for each identifier in the list. The form
647- with :keyword: `from ` performs step (1) once, and then performs step (2)
648- repeatedly.
645+ where the :keyword: `import ` statement occurs). The statement comes in two
646+ forms differing on whether it uses the :keyword: `from ` keyword. The first form
647+ (without :keyword: `from `) repeats these steps for each identifier in the list.
648+ The form with :keyword: `from ` performs step (1) once, and then performs step
649+ (2) repeatedly. For a reference implementation of step (1), see the
650+ :mod: `importlib ` module.
649651
650- In this context, to "initialize" a built-in or extension module means to call an
651- initialization function that the module must provide for the purpose (in the
652- reference implementation, the function's name is obtained by prepending string
653- "init" to the module's name); to "initialize" a Python-coded module means to
654- execute the module's body.
652+ .. index ::
653+ single: package
654+
655+ To understand how step (1) occurs, one must first understand how Python handles
656+ hierarchical naming of modules. To help organize modules and provide a
657+ hierarchy in naming, Python has a concept of packages. A package can contain
658+ other packages and modules while modules cannot contain other modules or
659+ packages. From a file system perspective, packages are directories and modules
660+ are files. The original `specification for packages
661+ <http://www.python.org/doc/essays/packages.html> `_ is still available to read,
662+ although minor details have changed since the writing of that document.
655663
656664.. index ::
657- single: modules (in module sys)
658- single: sys.modules
659- pair: module; name
660- pair: built-in; module
661- pair: user-defined; module
662- pair: filename; extension
663- triple: module; search; path
664- module: sys
665-
666- The system maintains a table of modules that have been or are being initialized,
667- indexed by module name. This table is accessible as ``sys.modules ``. When a
668- module name is found in this table, step (1) is finished. If not, a search for
669- a module definition is started. When a module is found, it is loaded. Details
670- of the module searching and loading process are implementation and platform
671- specific. It generally involves searching for a "built-in" module with the
672- given name and then searching a list of locations given as ``sys.path ``.
665+ single: sys.modules
666+
667+ Once the name of the module is known (unless otherwise specified, the term
668+ "module" will refer to both packages and modules), searching
669+ for the module or package can begin. The first place checked is
670+ :data: `sys.modules `, the cache of all modules that have been imported
671+ previously. If the module is found there then it is used in step (2) of import.
673672
674673.. index ::
675- pair: module; initialization
676- exception: ImportError
677- single: code block
678- exception: SyntaxError
674+ single: sys.meta_path
675+ single: finder
676+ pair: finder; find_module
677+ single: __path__
678+
679+ If the module is not found in the cache, then :data: `sys.meta_path ` is searched
680+ (the specification for :data: `sys.meta_path ` can be found in :pep: `302 `).
681+ The object is a list of :term: `finder ` objects which are queried in order as to
682+ whether they know how to load the module by calling their :meth: `find_module `
683+ method with the name of the module. If the module happens to be contained
684+ within a package (as denoted by the existence of a dot in the name), then a
685+ second argument to :meth: `find_module ` is given as the value of the
686+ :attr: `__path__ ` attribute from the parent package (everything up to the last
687+ dot in the name of the module being imported). If a finder can find the module
688+ it returns a :term: `loader ` (discussed later) or returns :keyword: `None `.
689+
690+ .. index ::
691+ single: sys.path_hooks
692+ single: sys.path_importer_cache
693+ single: sys.path
694+
695+ If none of the finders on :data: `sys.meta_path ` are able to find the module
696+ then some implicitly defined finders are queried. Implementations of Python
697+ vary in what implicit meta path finders are defined. The one they all do
698+ define, though, is one that handles :data: `sys.path_hooks `,
699+ :data: `sys.path_importer_cache `, and :data: `sys.path `.
700+
701+ The implicit finder searches for the requested module in the "paths" specified
702+ in one of two places ("paths" do not have to be file system paths). If the
703+ module being imported is supposed to be contained within a package then the
704+ second argument passed to :meth: `find_module `, :attr: `__path__ ` on the parent
705+ package, is used as the source of paths. If the module is not contained in a
706+ package then :data: `sys.path ` is used as the source of paths.
707+
708+ Once the source of paths is chosen it is iterated over to find a finder that
709+ can handle that path. The dict at :data: `sys.path_importer_cache ` caches
710+ finders for paths and is checked for a finder. If the path does not have a
711+ finder cached then :data: `sys.path_hooks ` is searched by calling each object in
712+ the list with a single argument of the path, returning a finder or raises
713+ :exc: `ImportError `. If a finder is returned then it is cached in
714+ :data: `sys.path_importer_cache ` and then used for that path entry. If no finder
715+ can be found but the path exists then a value of :keyword: `None ` is
716+ stored in :data: `sys.path_importer_cache ` to signify that an implicit,
717+ file-based finder that handles modules stored as individual files should be
718+ used for that path. If the path does not exist then a finder which always
719+ returns :keyword: `None ` is placed in the cache for the path.
720+
721+ .. index ::
722+ single: loader
723+ pair: loader; load_module
724+ exception: ImportError
725+
726+ If no finder can find the module then :exc: `ImportError ` is raised. Otherwise
727+ some finder returned a loader whose :meth: `load_module ` method is called with
728+ the name of the module to load (see :pep: `302 ` for the original definition of
729+ loaders). A loader has several responsibilities to perform on a module it
730+ loads. First, if the module already exists in :data: `sys.modules ` (a
731+ possibility if the loader is called outside of the import machinery) then it
732+ is to use that module for initialization and not a new module. But if the
733+ module does not exist in :data: `sys.modules ` then it is to be added to that
734+ dict before initialization begins. If an error occurs during loading of the
735+ module and it was added to :data: `sys.modules ` it is to be removed from the
736+ dict. If an error occurs but the module was already in :data: `sys.modules ` it
737+ is left in the dict.
738+
739+ .. index ::
740+ single: __name__
741+ single: __file__
742+ single: __path__
743+ single: __package__
744+ single: __loader__
745+
746+ The loader must set several attributes on the module. :data: `__name__ ` is to be
747+ set to the name of the module. :data: `__file__ ` is to be the "path" to the file
748+ unless the module is built-in (and thus listed in
749+ :data: `sys.builtin_module_names `) in which case the attribute is not set.
750+ If what is being imported is a package then :data: `__path__ ` is to be set to a
751+ list of paths to be searched when looking for modules and packages contained
752+ within the package being imported. :data: `__package__ ` is optional but should
753+ be set to the name of package that contains the module or package (the empty
754+ string is used for module not contained in a package). :data: `__loader__ ` is
755+ also optional but should be set to the loader object that is loading the
756+ module.
679757
680- If a built-in module is found, its built-in initialization code is executed and
681- step (1) is finished. If no matching file is found, :exc: `ImportError ` is
682- raised. If a file is found, it is parsed, yielding an executable code block. If
683- a syntax error occurs, :exc: `SyntaxError ` is raised. Otherwise, an empty module
684- of the given name is created and inserted in the module table, and then the code
685- block is executed in the context of this module. Exceptions during this
686- execution terminate step (1).
758+ .. index ::
759+ exception: ImportError
760+
761+ If an error occurs during loading then the loader raises :exc: `ImportError ` if
762+ some other exception is not already being propagated. Otherwise the loader
763+ returns the module that was loaded and initialized.
687764
688765When step (1) finishes without raising an exception, step (2) can begin.
689766
@@ -723,23 +800,21 @@ function contains or is a nested block with free variables, the compiler will
723800raise a :exc: `SyntaxError `.
724801
725802.. index ::
726- keyword: from
727- statement: from
728- triple: hierarchical; module; names
729- single: packages
730- single: __init__.py
731-
732- **Hierarchical module names: ** when the module names contains one or more dots,
733- the module search path is carried out differently. The sequence of identifiers
734- up to the last dot is used to find a "package"; the final identifier is then
735- searched inside the package. A package is generally a subdirectory of a
736- directory on ``sys.path `` that has a file :file: `__init__.py `.
737-
738- ..
739- [XXX Can't be
740- bothered to spell this out right now; see the URL
741- http://www.python.org/doc/essays/packages.html for more details, also about how
742- the module search works from inside a package.]
803+ single: relative; import
804+
805+ When specifying what module to import you do not have to specify the absolute
806+ name of the module. When a module or package is contained within another
807+ package it is possible to make a relative import within the same top package
808+ without having to mention the package name. By using leading dots in the
809+ specified module or package after :keyword: `from ` you can specify how high to
810+ traverse up the current package hierarchy without specifying exact names. One
811+ leading dot means the current package where the module making the import
812+ exists. Two dots means up one package level. Three dots is up two levels, etc.
813+ So if you execute ``from . import mod `` from a module in the ``pkg `` package
814+ then you will end up importing ``pkg.mod ``. If you execute ``from ..subpkg2
815+ imprt mod `` from within ``pkg.subpkg1 `` you will import ``pkg.subpkg2.mod ``.
816+ The specification for relative imports is contained within :pep: `328 `.
817+
743818
744819.. index :: builtin: __import__
745820
0 commit comments