为什么要使用importlib而不是exec import

时间:2018-06-10 20:21:52

标签: python python-3.x import exec python-importlib

在Python中,如果要动态导入模块(例如从字符串名称),可以使用模块importlib和函数importlib.import_module("foo"),它基本上提供与{{{{1}相同的结果。 1}}(但它是动态的)。

无论如何,在我的程序中,我使用函数从列表中导入模块,所以它看起来像这样:

import foo

我还没有在网络上的任何其他地方看到过这种类型的解决方案。我问的是,为什么?这是不好的做法,因为我使用# Note: this code does not produce the desired result. # Please see the snippet below, for the working version module_list = ["os"] def import_module(name): exec("global {}".format(name)) exec("import {}".format(name)) for item in module_list: import_module(item) 功能(因为我已经读过不做无数次),或者是因为它只是让人感到困惑

编辑:我觉得有必要注意它不是我上面的确切代码,但它是与这个问题实际相关的部分,而不是让人混淆

编辑(2):感谢用户Aran-Fey发现我的代码不起作用。我没有正确测试这个特定的片段。这是一个在python 3.6中运行的版本:

exec()

0 个答案:

没有答案