Skip to content

Instantly share code, notes, and snippets.

@stas00
Last active February 20, 2019 06:54
Show Gist options
  • Save stas00/d532a09f84128f785ca6cedfd9669ec4 to your computer and use it in GitHub Desktop.
Save stas00/d532a09f84128f785ca6cedfd9669ec4 to your computer and use it in GitHub Desktop.
Convert a string of a fully qualified function, class or module into its correspong python object, if such exists. See examples at the end.
import sys
def str2func(name):
"Convert a string of a fully qualified function, class or module into its python object"
if isinstance(name, str):
subpaths = name.split('.')
else:
return None
module = subpaths.pop(0)
if module in sys.modules:
obj = sys.modules[module]
else:
return None
for subpath in subpaths:
obj = getattr(obj, subpath, None)
if obj == None:
return None
return obj
import fastai.gen_doc.doctest
print(str2func('fastai.gen_doc.doctest.this_tests'))
import numpy
print(str2func('numpy.core.fromnumeric.any'))
print(str2func('numpy.core'))
import inspect
print(str2func('inspect.ismodule'))
print(str2func('inspect.doesnotexist'))
print(str2func('doesnotexist'))
# prints
#
# <function this_tests at 0x7f25067aa1e0>
# <function any at 0x7f250426eae8>
# <module 'numpy.core' from '.../python3.7/site-packages/numpy/core/__init__.py'>
# <function ismodule at 0x7f25194d80d0>
# None
# None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment