本文介绍了Python按字符串名称导入子模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用字符串列表(子模块的名称)导入当前模块中的子模块?
How can I use a list of strings ( names of submodules) to import submodules in current module ?
当前代码:
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))
这篇关于Python按字符串名称导入子模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!