source.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """
  2. This module adds several functions for interactive source code inspection.
  3. """
  4. from sympy.utilities.decorator import deprecated
  5. import inspect
  6. @deprecated(
  7. """
  8. The source() function is deprecated. Use inspect.getsource() instead, or
  9. if you are in IPython or Jupyter, the ?? feature.
  10. """,
  11. deprecated_since_version="1.3",
  12. active_deprecations_target="deprecated-source",
  13. )
  14. def source(object):
  15. """
  16. Prints the source code of a given object.
  17. .. deprecated:: 1.3
  18. The ``source()`` function is deprecated. Use ``inspect.getsource()`` or
  19. ``??`` in IPython/Jupyter instead.
  20. """
  21. print('In file: %s' % inspect.getsourcefile(object))
  22. print(inspect.getsource(object))
  23. def get_class(lookup_view):
  24. """
  25. Convert a string version of a class name to the object.
  26. For example, get_class('sympy.core.Basic') will return
  27. class Basic located in module sympy.core
  28. """
  29. if isinstance(lookup_view, str):
  30. mod_name, func_name = get_mod_func(lookup_view)
  31. if func_name != '':
  32. lookup_view = getattr(
  33. __import__(mod_name, {}, {}, ['*']), func_name)
  34. if not callable(lookup_view):
  35. raise AttributeError(
  36. "'%s.%s' is not a callable." % (mod_name, func_name))
  37. return lookup_view
  38. def get_mod_func(callback):
  39. """
  40. splits the string path to a class into a string path to the module
  41. and the name of the class.
  42. Examples
  43. ========
  44. >>> from sympy.utilities.source import get_mod_func
  45. >>> get_mod_func('sympy.core.basic.Basic')
  46. ('sympy.core.basic', 'Basic')
  47. """
  48. dot = callback.rfind('.')
  49. if dot == -1:
  50. return callback, ''
  51. return callback[:dot], callback[dot + 1:]