importstring.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # encoding: utf-8
  2. """
  3. A simple utility to import something by its string name.
  4. """
  5. # Copyright (c) IPython Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. from typing import Any
  8. def import_item(name: str) -> Any:
  9. """Import and return ``bar`` given the string ``foo.bar``.
  10. Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
  11. executing the code ``from foo import bar``.
  12. Parameters
  13. ----------
  14. name : string
  15. The fully qualified name of the module/package being imported.
  16. Returns
  17. -------
  18. mod : module object
  19. The module that was imported.
  20. """
  21. parts = name.rsplit(".", 1)
  22. if len(parts) == 2:
  23. # called with 'foo.bar....'
  24. package, obj = parts
  25. module = __import__(package, fromlist=[obj])
  26. try:
  27. pak = getattr(module, obj)
  28. except AttributeError as e:
  29. raise ImportError("No module named %s" % obj) from e
  30. return pak
  31. else:
  32. # called with un-dotted string
  33. return __import__(parts[0])