-1

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.

Homunculus Reticulli
  • 65,167
  • 81
  • 216
  • 341
  • Possible duplicate of [Saving an Object (Data persistence)](https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence) – Alexander McFarlane Sep 07 '18 at 09:44
  • @MehdiBenmoha I am not a professional developer. I have an IT background (academically, and many moons ago as a developer/consultant), but I don't "do IT" for a living - I'm NOT an IT professional. I work in a completely different domain. I only come on here to ask questions from IT professionals who do this for a living, when I need quick answers on side projects I happen to be working on in my spare time. So now you know! :) – Homunculus Reticulli Sep 07 '18 at 10:18

2 Answers2

1

I would suggest to not import that configuration file directly but write to functions to load and save the configuration (using json):

import json

def loadConfig():
    with open('config.py', 'w+') as configFile:
        try:
            config = json.loads(configFile.read())
        except ValueError:
            config = {}
        except:
            raise
        return config

def saveConfig(config):
    with open('config.py', 'w+') as configFile:
        configFile.write(json.dumps(config))

config = loadConfig()
config["foo"] = "bar"
saveConfig(config)

Or just use a ready to use module, which will handle config files for you.

Frieder
  • 1,208
  • 16
  • 25
0

If you want your settings to be writable, don't make them Python files. Use a text format: .ini is good because it can be read and written using the configparser module from the standard library.

Another alternative is YAML, which is easy to read and write for both machines and humans.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • `JSON` would be another option, given that `JSON` serialization and deserialization are part of a package typically shipped with standard python installations. – sobek Sep 07 '18 at 09:47
  • 3
    This is good info, but should not be an answer as it doesn't answer the question, comment would be more suitable. – ruohola Sep 07 '18 at 09:47