]>
Commit | Line | Data |
---|---|---|
4710c53d | 1 | """Backport of importlib.import_module from 3.x."""\r |
2 | # While not critical (and in no way guaranteed!), it would be nice to keep this\r | |
3 | # code compatible with Python 2.3.\r | |
4 | import sys\r | |
5 | \r | |
6 | def _resolve_name(name, package, level):\r | |
7 | """Return the absolute name of the module to be imported."""\r | |
8 | if not hasattr(package, 'rindex'):\r | |
9 | raise ValueError("'package' not set to a string")\r | |
10 | dot = len(package)\r | |
11 | for x in xrange(level, 1, -1):\r | |
12 | try:\r | |
13 | dot = package.rindex('.', 0, dot)\r | |
14 | except ValueError:\r | |
15 | raise ValueError("attempted relative import beyond top-level "\r | |
16 | "package")\r | |
17 | return "%s.%s" % (package[:dot], name)\r | |
18 | \r | |
19 | \r | |
20 | def import_module(name, package=None):\r | |
21 | """Import a module.\r | |
22 | \r | |
23 | The 'package' argument is required when performing a relative import. It\r | |
24 | specifies the package to use as the anchor point from which to resolve the\r | |
25 | relative import to an absolute import.\r | |
26 | \r | |
27 | """\r | |
28 | if name.startswith('.'):\r | |
29 | if not package:\r | |
30 | raise TypeError("relative imports require the 'package' argument")\r | |
31 | level = 0\r | |
32 | for character in name:\r | |
33 | if character != '.':\r | |
34 | break\r | |
35 | level += 1\r | |
36 | name = _resolve_name(name[level:], package, level)\r | |
37 | __import__(name)\r | |
38 | return sys.modules[name]\r |