diff options
| author | Jacob Kaplan-Moss <jacob@jacobian.org> | 2009-03-18 16:55:59 +0000 |
|---|---|---|
| committer | Jacob Kaplan-Moss <jacob@jacobian.org> | 2009-03-18 16:55:59 +0000 |
| commit | c485e236bd7e5ea40c64b2fe54d85dbb15b2fd39 (patch) | |
| tree | fc5e86abf39b69181b2084f5c39038f1811b6b44 /django/utils/importlib.py | |
| parent | ee2f04d79e5bca55637b9bb3301618738a4e342a (diff) | |
Fixed #8193: all dynamic imports in Django are now done correctly. I know this because Brett Cannon borrowed the time machine and brought Python 2.7's '`importlib` back for inclusion in Django. Thanks for the patch-from-the-future, Brett!
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10088 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django/utils/importlib.py')
| -rw-r--r-- | django/utils/importlib.py | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/django/utils/importlib.py b/django/utils/importlib.py new file mode 100644 index 0000000000..ef4d0e4a27 --- /dev/null +++ b/django/utils/importlib.py @@ -0,0 +1,36 @@ +# Taken from Python 2.7 with permission from/by the original author. +import sys + +def _resolve_name(name, package, level): + """Return the absolute name of the module to be imported.""" + if not hasattr(package, 'rindex'): + raise ValueError("'package' not set to a string") + dot = len(package) + for x in xrange(level, 1, -1): + try: + dot = package.rindex('.', 0, dot) + except ValueError: + raise ValueError("attempted relative import beyond top-level " + "package") + return "%s.%s" % (package[:dot], name) + + +def import_module(name, package=None): + """Import a module. + + The 'package' argument is required when performing a relative import. It + specifies the package to use as the anchor point from which to resolve the + relative import to an absolute import. + + """ + 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 = _resolve_name(name[level:], package, level) + __import__(name) + return sys.modules[name] |
