robert robert - 1 month ago 20
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

param3:
a: 4
b: 7
c: 9


And I would like to have variables
param1
,
param2
,
param3
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
locals()
and
globals()
functuons, but did not get how to use them for this.

Answer

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