robert robert - 4 months ago 48
YAML Question

Import settings from the file

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

for example I may have a file:

param1: 12345

param2: test11

a: 4
b: 7
c: 9

And I would like to have variables
in my code.

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

I have heard about
functuons, but did not get how to use them for this.


You can use locals()['newvarname'] = 12345 to create a new variable. And you can just read your file and fill in this structure as you'd like.

You may write a function to call it and import settings:

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(
    for pname in ydata:
        # assume the yaml file contains dict
        flocals[pname] = ydata[pname]  # merge caller's locals with new vars