Implement the PEP 302 protocol for get_filename() as

importlib.abc.ExecutionLoader. PyLoader now inherits from this ABC instead of
InspectLoader directly. Both PyLoader and PyPycLoader provide concrete
implementations of get_filename in terms of source_path and bytecode_path.
This commit is contained in:
Brett Cannon 2009-07-20 04:23:48 +00:00
parent 64ef00fa60
commit 6919427e94
6 changed files with 136 additions and 27 deletions

View file

@ -315,16 +315,10 @@ class PyLoader:
@module_for_loader
def load_module(self, module):
"""Load a source module."""
return self._load_module(module)
def _load_module(self, module):
"""Initialize a module from source."""
"""Initialize the module."""
name = module.__name__
code_object = self.get_code(module.__name__)
# __file__ may have been set by the caller, e.g. bytecode path.
if not hasattr(module, '__file__'):
module.__file__ = self.source_path(name)
module.__file__ = self.get_filename(name)
if self.is_package(name):
module.__path__ = [module.__file__.rsplit(path_sep, 1)[0]]
module.__package__ = module.__name__
@ -334,6 +328,15 @@ class PyLoader:
exec(code_object, module.__dict__)
return module
def get_filename(self, fullname):
"""Return the path to the source file, else raise ImportError."""
path = self.source_path(fullname)
if path is not None:
return path
else:
raise ImportError("no source path available for "
"{0!r}".format(fullname))
def get_code(self, fullname):
"""Get a code object from source."""
source_path = self.source_path(fullname)
@ -388,15 +391,16 @@ class PyPycLoader(PyLoader):
"""
@module_for_loader
def load_module(self, module):
"""Load a module from source or bytecode."""
name = module.__name__
source_path = self.source_path(name)
bytecode_path = self.bytecode_path(name)
# get_code can worry about no viable paths existing.
module.__file__ = source_path or bytecode_path
return self._load_module(module)
def get_filename(self, fullname):
"""Return the source or bytecode file path."""
path = self.source_path(fullname)
if path is not None:
return path
path = self.bytecode_path(fullname)
if path is not None:
return path
raise ImportError("no source or bytecode path available for "
"{0!r}".format(fullname))
def get_code(self, fullname):
"""Get a code object from source or bytecode."""