From: Fabian Seoane <fab...@fseoane.net> Function get_class returns a class from a given string. It makes use of get_mod_func
Implemented after a function with same name in django's codebase --- sympy/utilities/source.py | 30 ++++++++++++++++++++++++++++++ sympy/utilities/tests/test_source.py | 8 ++++++++ 2 files changed, 38 insertions(+), 0 deletions(-) create mode 100644 sympy/utilities/tests/test_source.py diff --git a/sympy/utilities/source.py b/sympy/utilities/source.py index 56ca7f7..213d3d8 100644 --- a/sympy/utilities/source.py +++ b/sympy/utilities/source.py @@ -10,3 +10,33 @@ def source(object): """ print 'In file: %s' % inspect.getsourcefile(object) print inspect.getsource(object) + +def get_class(lookup_view): + """ + Convert a string version of a class name to the object. + + For example, get_class('sympy.core.Basic') will return + class Basic located in module sympy.core + """ + if isinstance(lookup_view, str): + # Bail early for non-ASCII strings (they can't be functions). + lookup_view = lookup_view.encode('ascii') + mod_name, func_name = get_mod_func(lookup_view) + if func_name != '': + lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name) + if not callable(lookup_view): + raise AttributeError("'%s.%s' is not a callable." % (mod_name, func_name)) + return lookup_view + +def get_mod_func(callback): + """ + splits the string path to a class into a string path to the module + and the name of the class. For example: + >>> get_mod_func('sympy.core.basic.Basic') + ('sympy.core.basic', 'Basic') + """ + try: + dot = callback.rindex('.') + except ValueError: + return callback, '' + return callback[:dot], callback[dot+1:] \ No newline at end of file diff --git a/sympy/utilities/tests/test_source.py b/sympy/utilities/tests/test_source.py new file mode 100644 index 0000000..0716d46 --- /dev/null +++ b/sympy/utilities/tests/test_source.py @@ -0,0 +1,8 @@ +from sympy.utilities.source import get_mod_func, get_class + +def test_get_mod_func(): + assert get_mod_func('sympy.core.basic.Basic') == ('sympy.core.basic', 'Basic') + +def test_get_class(): + _basic = get_class('sympy.core.basic.Basic') + assert _basic.__name__ == 'Basic' \ No newline at end of file -- 1.6.1.2 --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "sympy-patches" group. To post to this group, send email to sympy-patches@googlegroups.com To unsubscribe from this group, send email to sympy-patches+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/sympy-patches?hl=en -~----------~----~----~----~------~----~------~--~---