如何使用字符串列表(子模块名称)来导入当前模块中的子模块?
当前代码:
from mainapp.utils import firstutil
from mainapp.utils import secondutil
from mainapp.utils import fifthutil
所需代码:
needed_utils = ["firstutil","secondutil","fifthutil"]
for util_name in needed_utils:
# use __import__ to achieve same effect as in current code
def getobj(astr):
"""
getobj('scipy.stats.stats') returns the associated module
getobj('scipy.stats.stats.chisquare') returns the associated function
"""
try:
return globals()[astr]
except KeyError:
try:
return __import__(astr, fromlist=[''])
except ImportError:
modname, _, basename = astr.rpartition('.')
if modname:
mod = getobj(modname)
return getattr(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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)