module_loading.py 842 B

12345678910111213141516171819202122232425262728293031
  1. from importlib import (
  2. import_module,
  3. )
  4. from typing import (
  5. Any,
  6. )
  7. def import_string(dotted_path: str) -> Any:
  8. """
  9. Import a variable using its path and name.
  10. :param dotted_path: dotted module path and variable/class name
  11. :return: the attribute/class designated by the last name in the path
  12. :raise: ImportError, if the import failed
  13. Source: django.utils.module_loading
  14. """
  15. try:
  16. module_path, class_name = dotted_path.rsplit(".", 1)
  17. except ValueError:
  18. msg = f"{dotted_path} doesn't look like a module path"
  19. raise ImportError(msg)
  20. module = import_module(module_path)
  21. try:
  22. return getattr(module, class_name)
  23. except AttributeError:
  24. msg = f'Module "{module_path}" does not define a "{class_name}" attribute/class'
  25. raise ImportError(msg)