1 """Backport of importlib.import_module from 3.x."""
2 # While not critical (and in no way guaranteed!), it would be nice to keep this
3 # code compatible with Python 2.3.
6 def _resolve_name(name
, package
, level
):
7 """Return the absolute name of the module to be imported."""
10 if package
.count('.') < level
:
11 raise ValueError("attempted relative import beyond top-level "
13 except AttributeError:
14 raise ValueError("'package' not set to a string")
16 # rpartition is more "correct" and rfind is just as easy to use, but
17 # neither are in Python 2.3.
18 dot_rindex
= package
.rindex('.', level
)
19 base
= package
[:dot_rindex
]
23 return "%s.%s" % (base
, name
)
28 def import_module(name
, package
=None):
31 The 'package' argument is required when performing a relative import. It
32 specifies the package to use as the anchor point from which to resolve the
33 relative import to an absolute import.
36 if name
.startswith('.'):
38 raise TypeError("relative imports require the 'package' argument")
40 for character
in name
:
44 name
= _resolve_name(name
[level
:], package
, level
)
45 # Try to import specifying the level to be as accurate as possible, but
46 # realize that keyword arguments are not found in Python 2.3.
48 __import__(name
, level
=0)
51 return sys
.modules
[name
]