I am using Python 3.5 and want to store my application configuration in a python file (e.g. settings.py).
Sample settings.py file
ALPHA = 0.1
BETA = {}
Pseudocode
import settings as conf
DEFAULT_ALPHA = 0.234
NEW_BETA = { 1: 2, 2: 'Hello'}
keys = [x for x in dir(conf) if x[0] != '_']
if 'ALPHA' not in keys:
conf.ALPHA = DEFAULT_ALPHA
if 'BETA' not in keys:
conf.BETA = {}
if not conf.BETA:
conf.beta = NEW_BETA
# How to write new configuration to file?
My question is how I would I then write the new configuration (settings.py) to file?
[[Addendum]]
As others have pointed out in the comments section (and even answers), the obvious way to do this would be to use one of the more common "structured data" formats: i.e. JSON, YML, XML etc.
I am aware of the json module (having used it several times in the past). However, I was intrigued by code I saw in a django app which seemed to be directly editing a configuration file (django aficionados would recognise settings.py).
I couldn't work out how the settings were being written back to file, and tried to replicate it - hence this question. FWIW, the JSON/YML approach is the obvious one I would have gone for otherwise (have done, several times in the past).
So, my question remains - is there a way to load a python module, modify it and then save it (the module) back to file?
There are actually many scenarios where this would be useful. One such example would be a django app that when installed, actually makes the appropriate changes in settings.py - so there is no need to add the application in INSTALLED_APPS variable of settings.py and no need to manually add the apps configurations to settings.py.
This would aid in deploying new apps in django projects, without having to use current workarounds like different versions of settings.py (for copying over in a Dockerfile for e.g), or even manually having to modify the settings.py file.