'Importing some variables from another file using importlib

I would like to know if it is possible to import some variables from another python file using importlib.import_module function (or another similar). I need to use importlib because in my project I employ a variable for the name of the file. For instance, if the name of the file was explicitly given - let this be myfile - I would use

from myfile import a, b

to import variables a and b. But for the case of myfile being a variable for the file name, I was thinking that I could use something like

import importlib
a = importlib.import_module(myfile.a)

However this seems to only work for the case of myfile being a variable for the name of a package and not a variable for the name of a file. If it is the case of the latter and the name of the file is for instance "foo", the error

No module named 'foo.a'; 'foo' is not a package

happens. Also, I did not find a way to import the additional variable b through the importlib.import_module function. Is there any importlib function that could do this?



Solution 1:[1]

We ended up using something like

imported_function = getattr(import_module(module_name), function_name)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Csala