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>You can use <code>locals()['newvarname'] = 12345</code> to create a new variable.
And you can just read your file and fill in this structure as you'd like.</p>

<p>You may write a function to call it and import settings:</p>

<pre><code>import sys
import yaml


def get_settings(filename):
    flocals = sys._getframe().f_back.f_locals  # get locals() from caller
    with open(filename, 'r') as ysfile:
        ydata = yaml.load(ysfile.read())
    for pname in ydata:
        # assume the yaml file contains dict
        flocals[pname] = ydata[pname]  # merge caller's locals with new vars
</code></pre>

python yaml