Last active
February 20, 2019 06:54
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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