如何在python中有选择地导入模块?

2024-10-01 11:37:34 发布

您现在位置:Python中文网/ 问答频道 /正文

根据不同的情况,我需要导入不同的模块,例如:

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

这些helper包含相同的字典dict01dict02dict03……但是在不同的情况下有不同的值被调用。在

但这也有一些问题:

  1. 导入语句都写在文件的顶部,但是这里的check_situation()函数需要先决条件,因此它现在离顶部还很远。在
  2. 不止一个文件需要这个helper模块,所以使用这种导入很困难也很难看。在

那么,如何重新安排这些帮手呢?在


Tags: 模块文件importhelperif字典checkas
3条回答

您可以使用__import__(),它接受一个字符串并返回该模块:

helper=__import__("helper_{0}".format(check_situation()))

示例:

^{pr2}$

正如@wim和python3.x文档中指出的那样,__import__()

Import a module. Because this function is meant for use by the Python interpreter and not for general use it is better to use importlib.import_module() to programmatically import a module.

我自己解决,是指@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_,那么wanted,无论在调用方文件中调用还是在调用此wanted的其他文件中调用,都将被重新定向到这个或那个\u模块。在

另外,因为我只在函数中导入re-undirect,所以您不会在其他任何地方看到这个模块,而只看到想要的。在

首先,没有严格要求import语句必须位于文件的顶部,这更像是一种风格指导。在

现在,importlibdict可以用来替换你的if/elif链:

import importlib

d = {1: 'helper_1', 2: 'helper_2'}
helper = importlib.import_module(d.get(check_situation(), 'helper_0'))

但这只是语法上的糖,真的,我想你还有更大的事要做。听起来你需要重新考虑你的数据结构,重新设计代码。在

任何时候,只要变量名为dict01dict02dict03这是一个确定的迹象,表明你需要准备一个级别,并有一些{}的容器,例如它们的列表。以数字结尾的“helper”模块名称也是如此。在

相关问题 更多 >