importstring.py 1.0 KB

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