importstring.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. """
  2. A simple utility to import something by its string name.
  3. """
  4. # Copyright (c) IPython Development Team.
  5. # Distributed under the terms of the Modified BSD License.
  6. from __future__ import annotations
  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. if not isinstance(name, str):
  22. raise TypeError("import_item accepts strings, not '%s'." % type(name))
  23. parts = name.rsplit(".", 1)
  24. if len(parts) == 2:
  25. # called with 'foo.bar....'
  26. package, obj = parts
  27. module = __import__(package, fromlist=[obj])
  28. try:
  29. pak = getattr(module, obj)
  30. except AttributeError as e:
  31. raise ImportError("No module named %s" % obj) from e
  32. return pak
  33. else:
  34. # called with un-dotted string
  35. return __import__(parts[0])