Import settings from the file
<p>I would like to import settings from a yaml file, but make them available as regular variables in the current context.</p>

<p>for example I may have a file:</p>

<pre><code>param1: 12345

param2: test11

param3:
    a: 4
    b: 7
    c: 9
</code></pre>

<p>And I would like to have variables <code>param1</code>, <code>param2</code>, <code>param3</code> in my code.</p>

<p>I may want to use this from any function and do not want to have them available globally.</p>

<p>I have heard about <code>locals()</code> and <code>globals()</code> functuons, but did not get how to use them for this.</p>

<p>Even though the trick is great in @baldr's answer, I suggest moving the variable assignments out of the function for better readability. Having a function change its caller's context seems very hard to remember and maintain. So, </p>

<pre><code>import yaml

def get_settings(filename):
    with open(filename, 'r') as yf:
        return yaml.load(yf.read())

def somewhere():
    locals().update(get_settings('foo.yaml'))
    print(param1)
</code></pre>

<p>Even then I would strongly suggest simply using the dictionary. Otherwise, you risk very strange bugs. For instance, what if your yaml file contains a <code>open</code> or a <code>print</code> key? They will override python's functions, so the <code>print(param1)</code> in the example will raise a <code>TypeError</code> exception.</p>

python yaml