I apologize if this is a basic question but I can’t seem to find the answer here or on Google. Basically I’m trying to create a single config module that would be available to all other modules imported in a python application. Of course it works if I have import config in each file but I would like to make my config dynamic based on the environment the application is running in and I’d prefer not to have to copy the logic into every file.
Here’s an example:
app.py:
import config
import submodule
# do other stuff
submodule.py:
print config.some_config_variable
But python of course complains that config isn’t defined.
I did find some stuff about global variables but that didn’t seem to work either. Here’s what I tried:
Edit I changed this to show that I’d like the actual config being imported to be dynamic. However I do currently have a static config modle for my tests just to figure out how to import globally and then worry about that logic
app.py
# logic here that defines some_dynamic_config
global config
config = __import__(some_dynamic_config)
import submodule
submodule.py
print config.some_config_variable
But config still isn’t defined.
I’m aware that I could create a single config.py and place logic to set the variables but I dislike that. I prefer the config file to just configuration and not contain a bunch of logic.
You’ve got to put your logic somewhere. Your
config.pycould be a module that determines which config files to load, something like this:With this approach, you can put common settings in common_settings.py, and platform-specific settings in their respective files. Since the platform-specific settings are imported after common_settings, you can also override anything in common_settings by defining it again in the platform-specific files.
This is a common pattern used in Django settings files, and works quite well there.
You could also wrap each
importcall withtry... except ImportError:blocks if need be.