我有几个不同的模块,我需要根据不同的情况导入其中一个模块,例如:
if check_situation() == 1:
import helper_1 as helper
elif check_situation() == 2:
import helper_2 as helper
elif ...
...
else:
import helper_0 as helper
这些助手包含相同的词典dict01
,dict02
,dict03
...但在不同情况下可以调用不同的值。
但这有一些问题:
check_situation()
函数需要先决条件才能使它现在远离顶层。那么,如何重新安排这些助手?
答案 0 :(得分:4)
您可以使用__import__()
,它接受一个字符串并返回该模块:
helper=__import__("helper_{0}".format(check_situation()))
示例:
In [10]: mod=__import__("{0}math".format(raw_input("enter 'c' or '': ")))
enter 'c' or '': c #imports cmath
In [11]: mod.__file__
Out[11]: '/usr/local/lib/python2.7/lib-dynload/cmath.so'
In [12]: mod=__import__("{0}math".format(raw_input("enter 'c' or '': ")))
enter 'c' or '':
In [13]: mod.__file__
Out[13]: '/usr/local/lib/python2.7/lib-dynload/math.so'
正如@wim和__import__()
上的python3.x文档所指出的那样:
导入模块。因为这个函数适合Python使用 口译员而不是一般用途,最好使用
importlib.import_module()
以编程方式导入模块。
答案 1 :(得分:3)
首先,没有严格要求import语句需要位于文件的顶部,它更像是一种样式指南。
现在,importlib
和dict
可用于替换您的if
/ elif
链:
import importlib
d = {1: 'helper_1', 2: 'helper_2'}
helper = importlib.import_module(d.get(check_situation(), 'helper_0'))
但它真的只是语法糖,我怀疑你有更大的鱼来炸。听起来你需要重新考虑你的数据结构,并重新设计代码。
任何时候你都有名为dict01
,dict02
,dict03
的变量,这是一个肯定的迹象,你需要提升一个级别,并拥有一些dicts
的容器例如他们的清单。您的'helper'模块名称以数字结尾也是如此。
答案 2 :(得分:1)
我同意其他答案中给出的方法更接近标题中提出的主要问题,但是如果导入模块的开销很低(因为可能导入几个字典)并且没有副作用在这种情况下,你可能最好导入它们,然后在模块中选择合适的字典:
import helper_0
import helper_1
...
helperList = [helper_0, helper_1, helper_2...]
...
helper = helperList[check_situation()]
答案 3 :(得分:1)
自己解决,提到@Michael Scott Cuthbert
# re_direct.py
import this_module
import that_module
wanted = None
# caller.py
import re-direct
'''
many prerequisites
'''
def imp_now(case):
import re_direct
if case1:
re_direct.wanted = re_direct.this_module
elif case2:
re_direct.wanted = re_direct.that_module
然后,如果在调用者中,我调用imp_now,然后想要,无论调用调用者文件还是其他调用此文件的文件,都会被重定向到this_or_that_module。
另外,因为我只在一个函数中导入re_direct,所以你不会在其他任何地方看到这个模块,但只看到想要的。