简体   繁体   English

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

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

This question was marked as duplicate . 这个问题被标记为重复 However the duplicate questions deals with modules while my question is asking for how to import parts of module. 然而, 重复的问题涉及模块,而我的问题是询问如何导入模块的部分。

I know that I can import certain portions of the module by using from mymodule import myfunction . 我知道我可以import通过使用该模块的某些部分from mymodule import myfunction What if want to import several things, but I need to list them as strings. 如果想要导入几个东西,但我需要将它们列为字符串。 For example: 例如:

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

I did ask this question , but it looks like I need to use the trick (if there is one) above for my code as well. 我确实问了这个问题 ,但看起来我需要使用上面的技巧(如果有的话)我的代码。

Any help is appreciated. 任何帮助表示赞赏。

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

If you want to be able to use the things which have been imported globally, then do: 如果您希望能够使用全局导入的内容,请执行以下操作:

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

To remove the imports, you can do 要删除导入,您可以这样做

del thing1

or 要么

del globals()['thing1']

Another useful operation you can do is to reload a module 您可以执行的另一项有用操作是reload模块

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

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