This is essentially a re-ask of my first question, which was closed without being answered properly. I'll try to be more verbose here and detail why the suggested duplicate fails to solve my issue.
The project I'm working on is being run in two distinct environments. To cope, we have two nearly identical files, say, here_file.py and there_file.py, that define the various hostnames, URLs, file paths, etc. that are unique to the environments. An environment variable controls the choice of file to import. That is, our imports include a section like:
if os.getenv('location') == 'here':
from here_file import A, very, long, list, of, variables
if os.getenv('location') == 'there':
from there_file import A, very, long, list, of, variables
The suggested duplicate shows how to use importlib.import_module()
to import different files depending on some condition. I had hoped a solution to this problem would look something like:
from importlib import import_module
var_file = import_module(f"{os.getenv('location')}_file")
from var_file import A, very, long, list, of, variables
Unfortunately, I was already able to get that far in my own testing. Here is a minimal example:
# here_file.py
variable = "I'm here."
# there_file.py
variable = "You're there."
# Option 1) This works, and is our current solution
import os
if os.getenv('location') == 'here':
from here_file import variable
if os.getenv('location') == 'there':
from there_file import variable
if __name__ == "__main__":
print("variable =", variable)
# Option 2) This works, but it isn't the answer I'm looking for
import os
from importlib import import_module
location = os.getenv('location')
location_module = import_module(f'{location}_file')
if __name__ == "__main__":
print("variable =", location_module.variable)
Here is what I would like to work, but fails:
# Option 3) This fails
import os
from importlib import import_module
location = os.getenv('location')
location_module = import_module(f'{location}_file')
from location_module import variable
if __name__ == "__main__":
print("variable =", variable)
fails with
Traceback (most recent call last):
File "import_fail.py", line 6, in <module>
from location_module import variable
ModuleNotFoundError: No module named 'location_module'
I think, perhaps, I should be using a loader or getattr()
... or something. The one-liner from import_module(f'{location}_file') import variable
hits a syntax error (though it'd be slick if it worked).
It may be that Option 3, importing variables from a dynamically specified module (which is how I phrased the question!), is impossible, in which case Option 2 will do.