.py config file with fallback data?
<p>I have a <code>settings.py</code> file in my project:</p>

<pre><code>"Nickname of the user to check the games for"
USERNAME = "user"
</code></pre>

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

<pre><code>USERNAME = "real-user"
</code></pre>

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

<p>I'm using Python 3</p>

<p>I assume the way you get the values from the <code>settings.py</code> file is by <code>import</code>ing it:</p>

<pre><code>import settings

print(settings.USERNAME)
</code></pre>

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

<p><strong><code>settings.py</code></strong> </p>

<pre><code>"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
</code></pre>

<p>Then after it's <code>import</code>ed, the <code>print(settings.USERNAME)</code> will display:</p>

<pre><code>real-user
</code></pre>

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

python python-3.x settings