_imports.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """
  2. A simple utility to import something by its string name.
  3. Vendored form ipython_genutils
  4. """
  5. # Copyright (c) IPython Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. from __future__ import annotations
  8. def import_item(name):
  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:
  29. raise ImportError("No module named %s" % obj) from None
  30. return pak
  31. # called with un-dotted string
  32. return __import__(parts[0])