Use a python variable name in yaml config

  python-3.x, yaml

I want to be able to use a python variable name inside a yaml config.

  • yml file
option1: a
option2: b
  • python file
# the python variables (note that these values can be modified by a program;
# thus, defining them directly in yml does not work)
a = 2
b = 3

# load yml
with open("example.yaml", "r") as stream:
    try:
        yml_config = yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

# desired output = a * 2 = 4
print(yml_config['option_1'] * 2)

# desired output = b * 2 = 6
print(yml_config['option_2'] * 2

Is there a way to gracefully do this?

Source: Python-3x Questions

LEAVE A COMMENT