繁体   English   中英

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

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

这个问题被标记为重复 然而, 重复的问题涉及模块,而我的问题是询问如何导入模块的部分。

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

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模块

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM