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."""
8 if not hasattr(package
, 'rindex'):
9 raise ValueError("'package' not set to a string")
11 for x
in xrange(level
, 1, -1):
13 dot
= package
.rindex('.', 0, dot
)
15 raise ValueError("attempted relative import beyond top-level "
17 return "%s.%s" % (package
[:dot
], name
)
20 def import_module(name
, package
=None):
23 The 'package' argument is required when performing a relative import. It
24 specifies the package to use as the anchor point from which to resolve the
25 relative import to an absolute import.
28 if name
.startswith('.'):
30 raise TypeError("relative imports require the 'package' argument")
32 for character
in name
:
36 name
= _resolve_name(name
[level
:], package
, level
)
38 return sys
.modules
[name
]