Baz
Baz

Reputation: 13135

Configuring a module with conditional imports

Lets say I have a module called config.py which contains data relating to the harware I'm connected to and I now wish to work with two different pieces of hardware, hw1 and hw2. config.py has access to a flag so it knows which hardware I'm working with. I wish to put specific hw1 config data in its own file and likewise for hw2.

So I now have something like this:

config.py
hw1_config.py
hw2_config.py

and then do a conditional import to import one or the other into config.py

if hw = "hw1":
   from hw1_conifg import * 
elif hw = "hw2":
   from hw2_conifg import * 

Is this a good approach?

Would it be possible for me to create folders within config.py's folder called hw1 and hw2 and move hw1_config.py into the hw1 folder, renaming it config.py. Likewise for hw2_config.py. How would the conditional imports look then?

config.py
/hw1/config.py
/hw2/config.py

I might also wish in the future to break up config.py into for example startup_config.py and shutdown_config.py. Again these files differ depending on the hw involved. What might be a good file/folder structure in this case?

config/startup.py 
config/shutdown.py
config/hw1/startup.py 
config/hw1/shutdown.py
config/hw2/startup.py 
config/hw2/shutdown.py

Upvotes: 0

Views: 134

Answers (1)

Anshul Goyal
Anshul Goyal

Reputation: 76887

I think the first solution looks all right

if hw = "hw1":
   from hw1_config import * 
elif hw = "hw2":
   from hw2_config import * 

If you plan to move the config files to separate folders, you can create a file __init__.py in each of the folders (hw1/__init__.py, hw2/__init__.py), and then, in your original config.py file, import the configs as below:

if hw = "hw1":
   from hw1.config import * 
elif hw = "hw2":
   from hw2.config import * 

As for the third structure, I think it a bit premature at this step - you could glob the file names within each directory, and then import them one by one.

Upvotes: 1

Related Questions