Skip to content Skip to sidebar Skip to footer

Importing Same Variable From Multiple Libraries

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 in

Solution 1:

If you have a file a.py:

var = 1

and a file b.py:

var = 2

you can do something like this:

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 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}

Post a Comment for "Importing Same Variable From Multiple Libraries"