source.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """
  2. This module adds several functions for interactive source code inspection.
  3. """
  4. def get_class(lookup_view):
  5. """
  6. Convert a string version of a class name to the object.
  7. For example, get_class('sympy.core.Basic') will return
  8. class Basic located in module sympy.core
  9. """
  10. if isinstance(lookup_view, str):
  11. mod_name, func_name = get_mod_func(lookup_view)
  12. if func_name != '':
  13. lookup_view = getattr(
  14. __import__(mod_name, {}, {}, ['*']), func_name)
  15. if not callable(lookup_view):
  16. raise AttributeError(
  17. "'%s.%s' is not a callable." % (mod_name, func_name))
  18. return lookup_view
  19. def get_mod_func(callback):
  20. """
  21. splits the string path to a class into a string path to the module
  22. and the name of the class.
  23. Examples
  24. ========
  25. >>> from sympy.utilities.source import get_mod_func
  26. >>> get_mod_func('sympy.core.basic.Basic')
  27. ('sympy.core.basic', 'Basic')
  28. """
  29. dot = callback.rfind('.')
  30. if dot == -1:
  31. return callback, ''
  32. return callback[:dot], callback[dot + 1:]