Rewrite the code implementing __import__ for importlib. Now it is much simpler

and relies much more on meta path finders to abstract out various parts of
import.

As part of this the semantics for import_module tightened up and now follow
__import__ much more closely (biggest thing is that the 'package' argument must
now already be imported, else a SystemError is raised).
This commit is contained in:
Brett Cannon 2009-02-07 01:15:27 +00:00
parent 887b3f2625
commit 2c318a1390
9 changed files with 117 additions and 502 deletions

View file

@ -29,7 +29,7 @@ def _set__import__():
"""Set __import__ to an instance of Import."""
global original__import__
original__import__ = __import__
__builtins__['__import__'] = Import()
__builtins__['__import__'] = _bootstrap._import
def _reset__import__():
@ -114,7 +114,7 @@ marshal._r_long = _r_long
# Public API #########################################################
__import__ = _bootstrap.Import().__call__
__import__ = _bootstrap._import
def import_module(name, package=None):
@ -125,17 +125,15 @@ def import_module(name, package=None):
relative import to an absolute import.
"""
level = 0
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
level = 0
for character in name:
if character != '.':
break
level += 1
name = Import._resolve_name(name[level:], package, level)
__import__(name)
return sys.modules[name]
return _bootstrap._gcd_import(name[level:], package, level)
# XXX This should go away once the public API is done.