importlib.py 1.5 KB

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