importstring.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 ipython_genutils.py3compat import cast_bytes_py2
  8. from six import string_types
  9. def import_item(name):
  10. """Import and return ``bar`` given the string ``foo.bar``.
  11. Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
  12. executing the code ``from foo import bar``.
  13. Parameters
  14. ----------
  15. name : string
  16. The fully qualified name of the module/package being imported.
  17. Returns
  18. -------
  19. mod : module object
  20. The module that was imported.
  21. """
  22. if not isinstance(name, string_types):
  23. raise TypeError("import_item accepts strings, not '%s'." % type(name))
  24. name = cast_bytes_py2(name)
  25. parts = name.rsplit('.', 1)
  26. if len(parts) == 2:
  27. # called with 'foo.bar....'
  28. package, obj = parts
  29. module = __import__(package, fromlist=[obj])
  30. try:
  31. pak = getattr(module, obj)
  32. except AttributeError:
  33. raise ImportError('No module named %s' % obj)
  34. return pak
  35. else:
  36. # called with un-dotted string
  37. return __import__(parts[0])