|
0
|
1 |
# Taken from Python 2.7 with permission from/by the original author. |
|
|
2 |
import sys |
|
|
3 |
|
|
|
4 |
def _resolve_name(name, package, level): |
|
|
5 |
"""Return the absolute name of the module to be imported.""" |
|
|
6 |
if not hasattr(package, 'rindex'): |
|
|
7 |
raise ValueError("'package' not set to a string") |
|
|
8 |
dot = len(package) |
|
|
9 |
for x in xrange(level, 1, -1): |
|
|
10 |
try: |
|
|
11 |
dot = package.rindex('.', 0, dot) |
|
|
12 |
except ValueError: |
|
|
13 |
raise ValueError("attempted relative import beyond top-level " |
|
|
14 |
"package") |
|
|
15 |
return "%s.%s" % (package[:dot], name) |
|
|
16 |
|
|
|
17 |
|
|
|
18 |
def import_module(name, package=None): |
|
|
19 |
"""Import a module. |
|
|
20 |
|
|
|
21 |
The 'package' argument is required when performing a relative import. It |
|
|
22 |
specifies the package to use as the anchor point from which to resolve the |
|
|
23 |
relative import to an absolute import. |
|
|
24 |
|
|
|
25 |
""" |
|
|
26 |
if name.startswith('.'): |
|
|
27 |
if not package: |
|
|
28 |
raise TypeError("relative imports require the 'package' argument") |
|
|
29 |
level = 0 |
|
|
30 |
for character in name: |
|
|
31 |
if character != '.': |
|
|
32 |
break |
|
|
33 |
level += 1 |
|
|
34 |
name = _resolve_name(name[level:], package, level) |
|
|
35 |
__import__(name) |
|
|
36 |
return sys.modules[name] |