Back to index

python3.2  3.2.2
Classes | Functions | Variables
importlib._bootstrap Namespace Reference

Classes

class  BuiltinImporter
class  FrozenImporter
class  _LoaderBasics
class  SourceLoader
class  _FileLoader
class  _SourceFileLoader
class  _SourcelessFileLoader
class  _ExtensionFileLoader
class  PathFinder
class  _FileFinder
class  _SourceFinderDetails
class  _SourcelessFinderDetails
class  _ExtensionFinderDetails
class  _DefaultPathFinder
class  _ImportLockContext

Functions

def _path_join
def _path_exists
def _path_is_mode_type
def _path_isfile
def _path_isdir
def _path_without_ext
def _path_absolute
def _wrap
def set_package
def set_loader
def module_for_loader
def _check_name
def _requires_builtin
def _requires_frozen
def _suffix_list
def _file_path_hook
def _gcd_import
def __import__

Variables

tuple code_type = type(_wrap.__code__)
 _DEFAULT_PATH_HOOK = _file_path_hook
list _IMPLICIT_META_PATH = [BuiltinImporter, FrozenImporter, _DefaultPathFinder]
string _ERR_MSG = 'No module named {}'

Detailed Description

Core implementation of import.

This module is NOT meant to be directly imported! It has been designed such
that it can be bootstrapped into Python as the implementation of import. As
such it requires the injection of specific modules and attributes in order to
work. One should use importlib as the public-facing version of this module.

Function Documentation

def importlib._bootstrap.__import__ (   name,
  globals = {},
  locals = {},
  fromlist = [],
  level = 0 
)
Import a module.

The 'globals' argument is used to infer where the import is occuring from
to handle relative imports. The 'locals' argument is ignored. The
'fromlist' argument specifies what should exist as attributes on the module
being imported (e.g. ``from module import <fromlist>``).  The 'level'
argument represents the package location to import from in a relative
import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).

Definition at line 841 of file _bootstrap.py.

00841 
00842 def __import__(name, globals={}, locals={}, fromlist=[], level=0):
00843     """Import a module.
00844 
00845     The 'globals' argument is used to infer where the import is occuring from
00846     to handle relative imports. The 'locals' argument is ignored. The
00847     'fromlist' argument specifies what should exist as attributes on the module
00848     being imported (e.g. ``from module import <fromlist>``).  The 'level'
00849     argument represents the package location to import from in a relative
00850     import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
00851 
00852     """
00853     if not hasattr(name, 'rpartition'):
00854         raise TypeError("module name must be str, not {}".format(type(name)))
00855     if level == 0:
00856         module = _gcd_import(name)
00857     else:
00858         # __package__ is not guaranteed to be defined or could be set to None
00859         # to represent that it's proper value is unknown
00860         package = globals.get('__package__')
00861         if package is None:
00862             package = globals['__name__']
00863             if '__path__' not in globals:
00864                 package = package.rpartition('.')[0]
00865         module = _gcd_import(name, package, level)
00866     # The hell that is fromlist ...
00867     if not fromlist:
00868         # Return up to the first dot in 'name'. This is complicated by the fact
00869         # that 'name' may be relative.
00870         if level == 0:
00871             return sys.modules[name.partition('.')[0]]
00872         elif not name:
00873             return module
00874         else:
00875             cut_off = len(name) - len(name.partition('.')[0])
00876             return sys.modules[module.__name__[:-cut_off]]
00877     else:
00878         # If a package was imported, try to import stuff from fromlist.
00879         if hasattr(module, '__path__'):
00880             if '*' in fromlist and hasattr(module, '__all__'):
00881                 fromlist = list(fromlist)
00882                 fromlist.remove('*')
00883                 fromlist.extend(module.__all__)
00884             for x in (y for y in fromlist if not hasattr(module,y)):
00885                 try:
00886                     _gcd_import('{0}.{1}'.format(module.__name__, x))
00887                 except ImportError:
00888                     pass
00889         return module

Here is the call graph for this function:

def importlib._bootstrap._check_name (   method) [private]
Decorator to verify that the module being requested matches the one the
loader can handle.

The first argument (self) must define _name which the second argument is
compared against. If the comparison fails then ImportError is raised.

Definition at line 150 of file _bootstrap.py.

00150 
00151 def _check_name(method):
00152     """Decorator to verify that the module being requested matches the one the
00153     loader can handle.
00154 
00155     The first argument (self) must define _name which the second argument is
00156     compared against. If the comparison fails then ImportError is raised.
00157 
00158     """
00159     def inner(self, name, *args, **kwargs):
00160         if self._name != name:
00161             raise ImportError("loader cannot handle %s" % name)
00162         return method(self, name, *args, **kwargs)
00163     _wrap(inner, method)
00164     return inner
00165 

Here is the call graph for this function:

def importlib._bootstrap._file_path_hook (   path) [private]
If the path is a directory, return a file-based finder.

Definition at line 713 of file _bootstrap.py.

00713 
00714 def _file_path_hook(path):
00715     """If the path is a directory, return a file-based finder."""
00716     if _path_isdir(path):
00717         return _FileFinder(path, _ExtensionFinderDetails(),
00718                            _SourceFinderDetails(),
00719                            _SourcelessFinderDetails())
00720     else:
00721         raise ImportError("only directories are supported")
00722 

Here is the call graph for this function:

def importlib._bootstrap._gcd_import (   name,
  package = None,
  level = 0 
) [private]
Import and return the module based on its name, the package the call is
being made from, and the level adjustment.

This function represents the greatest common denominator of functionality
between import_module and __import__. This includes settting __package__ if
the loader did not.

Definition at line 763 of file _bootstrap.py.

00763 
00764 def _gcd_import(name, package=None, level=0):
00765     """Import and return the module based on its name, the package the call is
00766     being made from, and the level adjustment.
00767 
00768     This function represents the greatest common denominator of functionality
00769     between import_module and __import__. This includes settting __package__ if
00770     the loader did not.
00771 
00772     """
00773     if package:
00774         if not hasattr(package, 'rindex'):
00775             raise ValueError("__package__ not set to a string")
00776         elif package not in sys.modules:
00777             msg = ("Parent module {0!r} not loaded, cannot perform relative "
00778                    "import")
00779             raise SystemError(msg.format(package))
00780     if not name and level == 0:
00781         raise ValueError("Empty module name")
00782     if level > 0:
00783         dot = len(package)
00784         for x in range(level, 1, -1):
00785             try:
00786                 dot = package.rindex('.', 0, dot)
00787             except ValueError:
00788                 raise ValueError("attempted relative import beyond "
00789                                  "top-level package")
00790         if name:
00791             name = "{0}.{1}".format(package[:dot], name)
00792         else:
00793             name = package[:dot]
00794     with _ImportLockContext():
00795         try:
00796             module = sys.modules[name]
00797             if module is None:
00798                 message = ("import of {} halted; "
00799                             "None in sys.modules".format(name))
00800                 raise ImportError(message)
00801             return module
00802         except KeyError:
00803             pass
00804         parent = name.rpartition('.')[0]
00805         path = None
00806         if parent:
00807             if parent not in sys.modules:
00808                 _gcd_import(parent)
00809             # Backwards-compatibility; be nicer to skip the dict lookup.
00810             parent_module = sys.modules[parent]
00811             try:
00812                 path = parent_module.__path__
00813             except AttributeError:
00814                 msg = (_ERR_MSG + '; {} is not a package').format(name, parent)
00815                 raise ImportError(msg)
00816         meta_path = sys.meta_path + _IMPLICIT_META_PATH
00817         for finder in meta_path:
00818             loader = finder.find_module(name, path)
00819             if loader is not None:
00820                 loader.load_module(name)
00821                 break
00822         else:
00823             raise ImportError(_ERR_MSG.format(name))
00824         # Backwards-compatibility; be nicer to skip the dict lookup.
00825         module = sys.modules[name]
00826         if parent:
00827             # Set the module as an attribute on its parent.
00828             setattr(parent_module, name.rpartition('.')[2], module)
00829         # Set __package__ if the loader did not.
00830         if not hasattr(module, '__package__') or module.__package__ is None:
00831             # Watch out for what comes out of sys.modules to not be a module,
00832             # e.g. an int.
00833             try:
00834                 module.__package__ = module.__name__
00835                 if not hasattr(module, '__path__'):
00836                     module.__package__ = module.__package__.rpartition('.')[0]
00837             except AttributeError:
00838                 pass
00839         return module
00840 

Here is the call graph for this function:

Here is the caller graph for this function:

def importlib._bootstrap._path_absolute (   path) [private]
Replacement for os.path.abspath.

Definition at line 70 of file _bootstrap.py.

00070 
00071 def _path_absolute(path):
00072     """Replacement for os.path.abspath."""
00073     if not path:
00074         path = _os.getcwd()
00075     try:
00076         return _os._getfullpathname(path)
00077     except AttributeError:
00078         if path.startswith('/'):
00079             return path
00080         else:
00081             return _path_join(_os.getcwd(), path)
00082 

Here is the call graph for this function:

def importlib._bootstrap._path_exists (   path) [private]
Replacement for os.path.exists.

Definition at line 28 of file _bootstrap.py.

00028 
00029 def _path_exists(path):
00030     """Replacement for os.path.exists."""
00031     try:
00032         _os.stat(path)
00033     except OSError:
00034         return False
00035     else:
00036         return True
00037 

def importlib._bootstrap._path_is_mode_type (   path,
  mode 
) [private]
Test whether the path is the specified mode type.

Definition at line 38 of file _bootstrap.py.

00038 
00039 def _path_is_mode_type(path, mode):
00040     """Test whether the path is the specified mode type."""
00041     try:
00042         stat_info = _os.stat(path)
00043     except OSError:
00044         return False
00045     return (stat_info.st_mode & 0o170000) == mode
00046 
00047 
# XXX Could also expose Modules/getpath.c:isfile()

Here is the caller graph for this function:

def importlib._bootstrap._path_isdir (   path) [private]
Replacement for os.path.isdir.

Definition at line 54 of file _bootstrap.py.

00054 
00055 def _path_isdir(path):
00056     """Replacement for os.path.isdir."""
00057     if not path:
00058         path = _os.getcwd()
00059     return _path_is_mode_type(path, 0o040000)
00060 

Here is the call graph for this function:

Here is the caller graph for this function:

def importlib._bootstrap._path_isfile (   path) [private]
Replacement for os.path.isfile.

Definition at line 48 of file _bootstrap.py.

00048 
00049 def _path_isfile(path):
00050     """Replacement for os.path.isfile."""
00051     return _path_is_mode_type(path, 0o100000)
00052 
00053 
# XXX Could also expose Modules/getpath.c:isdir()

Here is the call graph for this function:

Here is the caller graph for this function:

def importlib._bootstrap._path_join (   args) [private]
Replacement for os.path.join.

Definition at line 22 of file _bootstrap.py.

00022 
00023 def _path_join(*args):
00024     """Replacement for os.path.join."""
00025     return path_sep.join(x[:-len(path_sep)] if x.endswith(path_sep) else x
00026                             for x in args if x)
00027 

Here is the caller graph for this function:

def importlib._bootstrap._path_without_ext (   path,
  ext_type 
) [private]
Replacement for os.path.splitext()[0].

Definition at line 61 of file _bootstrap.py.

00061 
00062 def _path_without_ext(path, ext_type):
00063     """Replacement for os.path.splitext()[0]."""
00064     for suffix in _suffix_list(ext_type):
00065         if path.endswith(suffix):
00066             return path[:-len(suffix)]
00067     else:
00068         raise ValueError("path is not of the specified type")
00069 

Here is the call graph for this function:

def importlib._bootstrap._requires_builtin (   fxn) [private]
Decorator to verify the named module is built-in.

Definition at line 166 of file _bootstrap.py.

00166 
00167 def _requires_builtin(fxn):
00168     """Decorator to verify the named module is built-in."""
00169     def wrapper(self, fullname):
00170         if fullname not in sys.builtin_module_names:
00171             raise ImportError("{0} is not a built-in module".format(fullname))
00172         return fxn(self, fullname)
00173     _wrap(wrapper, fxn)
00174     return wrapper
00175 

Here is the call graph for this function:

def importlib._bootstrap._requires_frozen (   fxn) [private]
Decorator to verify the named module is frozen.

Definition at line 176 of file _bootstrap.py.

00176 
00177 def _requires_frozen(fxn):
00178     """Decorator to verify the named module is frozen."""
00179     def wrapper(self, fullname):
00180         if not imp.is_frozen(fullname):
00181             raise ImportError("{0} is not a frozen module".format(fullname))
00182         return fxn(self, fullname)
00183     _wrap(wrapper, fxn)
00184     return wrapper
00185 

Here is the call graph for this function:

def importlib._bootstrap._suffix_list (   suffix_type) [private]
Return a list of file suffixes based on the imp file type.

Definition at line 186 of file _bootstrap.py.

00186 
00187 def _suffix_list(suffix_type):
00188     """Return a list of file suffixes based on the imp file type."""
00189     return [suffix[0] for suffix in imp.get_suffixes()
00190             if suffix[2] == suffix_type]
00191 
00192 
00193 # Loaders #####################################################################

Here is the caller graph for this function:

def importlib._bootstrap._wrap (   new,
  old 
) [private]
Simple substitute for functools.wraps.

Definition at line 83 of file _bootstrap.py.

00083 
00084 def _wrap(new, old):
00085     """Simple substitute for functools.wraps."""
00086     for replace in ['__module__', '__name__', '__doc__']:
00087         setattr(new, replace, getattr(old, replace))
00088     new.__dict__.update(old.__dict__)
00089 

Here is the call graph for this function:

Here is the caller graph for this function:

Decorator to handle selecting the proper module for loaders.

The decorated function is passed the module to use instead of the module
name. The module passed in to the function is either from sys.modules if
it already exists or is a new module which has __name__ set and is inserted
into sys.modules. If an exception is raised and the decorator created the
module it is subsequently removed from sys.modules.

The decorator assumes that the decorated function takes the module name as
the second argument.

Definition at line 118 of file _bootstrap.py.

00118 
00119 def module_for_loader(fxn):
00120     """Decorator to handle selecting the proper module for loaders.
00121 
00122     The decorated function is passed the module to use instead of the module
00123     name. The module passed in to the function is either from sys.modules if
00124     it already exists or is a new module which has __name__ set and is inserted
00125     into sys.modules. If an exception is raised and the decorator created the
00126     module it is subsequently removed from sys.modules.
00127 
00128     The decorator assumes that the decorated function takes the module name as
00129     the second argument.
00130 
00131     """
00132     def decorated(self, fullname, *args, **kwargs):
00133         module = sys.modules.get(fullname)
00134         is_reload = bool(module)
00135         if not is_reload:
00136             # This must be done before open() is called as the 'io' module
00137             # implicitly imports 'locale' and would otherwise trigger an
00138             # infinite loop.
00139             module = imp.new_module(fullname)
00140             sys.modules[fullname] = module
00141         try:
00142             return fxn(self, module, *args, **kwargs)
00143         except:
00144             if not is_reload:
00145                 del sys.modules[fullname]
00146             raise
00147     _wrap(decorated, fxn)
00148     return decorated
00149 

Here is the call graph for this function:

Set __loader__ on the returned module.

Definition at line 107 of file _bootstrap.py.

00107 
00108 def set_loader(fxn):
00109     """Set __loader__ on the returned module."""
00110     def wrapper(self, *args, **kwargs):
00111         module = fxn(self, *args, **kwargs)
00112         if not hasattr(module, '__loader__'):
00113             module.__loader__ = self
00114         return module
00115     _wrap(wrapper, fxn)
00116     return wrapper
00117 

Here is the call graph for this function:

Set __package__ on the returned module.

Definition at line 94 of file _bootstrap.py.

00094 
00095 def set_package(fxn):
00096     """Set __package__ on the returned module."""
00097     def wrapper(*args, **kwargs):
00098         module = fxn(*args, **kwargs)
00099         if not hasattr(module, '__package__') or module.__package__ is None:
00100             module.__package__ = module.__name__
00101             if not hasattr(module, '__path__'):
00102                 module.__package__ = module.__package__.rpartition('.')[0]
00103         return module
00104     _wrap(wrapper, fxn)
00105     return wrapper
00106 

Here is the call graph for this function:


Variable Documentation

Definition at line 723 of file _bootstrap.py.

Definition at line 761 of file _bootstrap.py.

Definition at line 759 of file _bootstrap.py.

tuple importlib._bootstrap.code_type = type(_wrap.__code__)

Definition at line 90 of file _bootstrap.py.