仅导入模块的某些部分,但将这些部分列为字符串

import only some parts of a module, but list those parts as strings

这个问题被标记为 duplicate. However the duplicate 问题涉及模块,而我的问题是询问如何导入部分模块。

我知道我可以使用 from mymodule import myfunction import 模块的某些部分。如果想要导入几样东西,但我需要将它们列为字符串怎么办。例如:

import_things = ['thing1', 'thing2', 'thing2']
from mymodule import import_things

我确实问过 ,但看起来我也需要为我的代码使用上面的技巧(如果有的话)。

感谢任何帮助。

import importlib

base_module = importlib.import_module('mymodule')
imported_things = {thing: getattr(base_module, thing) for thing in import_things}

imported_things['thing1']() # Function call

如果你想使用全局导入的东西,那么做:

globals().update(imported_things)
thing1() # function call

要删除导入,您可以这样做

del thing1

del globals()['thing1']

你可以做的另一个有用的操作是reload一个模块