marmistrz marmistrz - 2 months ago 11
Python Question

.py config file with fallback data?

I have a

settings.py
file in my project:

"Nickname of the user to check the games for"
USERNAME = "user"


Unfortunately, it will be overwritten by each upgrade. So, I'd like to allow the user to override the default settings by creating a
.py
file
$XDG_CONFIG_HOME/myapp/config.py
, containing for example

USERNAME = "real-user"


Is it possible to modify
settings.py
so that it sucks any variables from the
.../config.py
file in a generic way, something like including this file at the end of
config.py
?

I'm using Python 3

Answer

I assume the way you get the values from the settings.py file is by importing it:

import settings

print(settings.USERNAME)

Then you could change it by adding something like this to the end which will do what you want.

settings.py

"Nickname of the user to check the games for"
USERNAME = "user"

def _read_overrides(filename):
    localdict = {}  # populated by exec
    try:
        with open(filename) as file:
            exec(compile(file.read(), filename, 'exec'),
                 {'__builtins__': None}, localdict)
    except FileNotFoundError:
        pass

    return localdict

for key, value in _read_overrides('config.py').items():
    globals()[key] = value

Then after it's imported, the print(settings.USERNAME) will display:

real-user

Also note the config.py overrides file can be named anything (it's doesn't need a .py extension).

Comments