The format is just plain executable Python source code.
This format is generally not used when you need to programmatically change the contents, but a human being with some basic Python knowledge can edit it in a simple text editor.
For example, to change Sara's phone number in your text editor, you just go to this line:
'phone' : '111 111 111'
… and change it to this:
'phone' : '888 888 888'
Similarly, to add another person, you can copy and paste one of the existing people's entries and edit it.
But if you wanted to have your script edit this file, it would need to parse the Python source (e.g., using the ast
module), map the assignments to a set of key-value pairs, modify the value, turn the result back into a set of assignments, then turn that back into source code. Or it could do something a little simpler and hackier with the same effect. But the point is, there's no clear and easy way to edit this file programmatically. I don't want to provide code that does this parsing and generating, because it's really not something you should be doing if you don't know how, and haven't thought through the safety implications, etc.
If you want a config file you can edit programmatically, replace it with something like JSON. That's just as easy for a human to edit, but it has the added benefit of also being easy for your program to edit, and being inherently safe from mistaken or malicious bad data.
If you or your users already have deployments using the config.py
format, you can write migration code that falls back to the "legacy" config file if the JSON file can't be found, something like this:
try:
with open('config.json') as f:
config = json.load(f)
except FileNotFoundError:
try:
import config
except Exception as e:
raise SomeMoreAopropriateError(…)
with open('config.json', 'w') as f:
json.dump(config, f)
(If the old code used, e.g., execfile
instead of import
, do the same thing here, of course.)