从多个库导入相同的变量 [英] Importing same variable from multiple libraries

查看:179
本文介绍了从多个库导入相同的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约20个不同的模块,它们都包含一个具有相同名称的变量。我试图导入这些变量,而不必明确键入每个导入。所以不要这样做:

I have a around 20 different modules that all contain a variable with the same name. I am trying to import these variables without having to explicitly type out every import. So instead of doing this:

import a,b,c,d,e

a1 = a.var
b1 = b.var
c1 = c.var
d1 = d.var
e1 = e.var

我想有一种动态创建它们的循环。类似于:

I would like to have some kind of loop that creates these dynamically. Something like:

module_list = [a,b,c,d,e]

for module in module_list:
    create module.var

答案可能在字典中的某处,但我我不太清楚在这里如何使用它们。

The answer probably lies somewhere in dictionaries but I'm not quite sure how exactly to use them here.

推荐答案

如果你有一个文件 a.py

var = 1

和文件 b.py

var = 2

你可以这样做:

from importlib import import_module

module_list = ['a', 'b']
variables = {}
for mod_name in module_list:
    mod = import_module(mod_name)
    variables[mod_name] = getattr(mod, 'var')

>>> variables
{'a': 1, 'b': 2}
>>> variables['a']
1

importlib.import_module 允许使用字符串作为名称导入模块。您可以使用 getattr()再次检索属性使用字符串作为其名称,例如:

importlib.import_module allows to import a module using a string as the name. You can use getattr() to retrieve an attribute again using a string for its name, for example:

>>> import sys
>>> sys.version == getattr(sys, 'version')
True

如果你是在单行中,你可以在一行中完成:

If you are into one-liners, you can do it in one line:

variables = {mod_name: getattr(import_module(mod_name), 'var') for mod_name in module_list}

这篇关于从多个库导入相同的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆