Python Import Submodules By String Names?
How can I use a list of strings ( names of submodules) to import submodules in current module ? Current code: from mainapp.utils import firstutil from mainapp.utils import secondut
Solution 1:
defgetobj(astr):
"""
getobj('scipy.stats.stats') returns the associated module
getobj('scipy.stats.stats.chisquare') returns the associated function
"""try:
returnglobals()[astr]
except KeyError:
try:
return__import__(astr, fromlist=[''])
except ImportError:
modname, _, basename = astr.rpartition('.')
if modname:
mod = getobj(modname)
returngetattr(mod, basename)
else:
raise
needed_utils = ["firstutil", "secondutil", "fifthutil"]
for util_name in needed_utils:
globals()[util_name] = getobj('mainapp.utils.{m}'.format(m=util_name))
Solution 2:
The thing that's confusing about the __import__ function is that you need to pass the fromlist
argument to do what you want:
mod1 = __import__('foo.bar') # returns the "foo" modulemod2 = __import__('foo.bar', fromlist=['thing_in_module']) # returns the "bar" module
As C.B. notes in a comment, a more full explanation can be found at Python's __import__ doesn't work as expected
Post a Comment for "Python Import Submodules By String Names?"