marmistrz marmistrz - 1 month ago 6
Python Question

.py config file with fallback data?

I have a
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
, containing for example

USERNAME = "real-user"

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

I'm using Python 3


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

import settings


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

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

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

    return localdict

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

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


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