gpt4 book ai didi

Python 按字符串名称导入子模块?

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:06 24 4
gpt4 key购买 nike

如何使用字符串列表(子模块的名称)在当前模块中导入子模块?

当前代码:

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 按字符串名称导入子模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23086369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com