Search code examples
pythonyamlpyyaml

Variables and their values are stored externally in a YAML file. How to read them as if I declare them internally?


Instead of having to declare the variables and their values in the script, I would like to have them declared externally in a separate YAML file called settings.yml:

setting1: cat
setting2: dog

Is there a way to use the variables' names and values directly as if I declare them internally? E.g. running print(setting1, setting2) returns cat dog. So far I can only read it:

import yaml

with open("settings.yml", "r") as stream:
    try:
        data = yaml.safe_load(stream)
        for key, value in data.items():
            print(f"{key}: {value}")
    except yaml.YAMLError as exc:
        print(exc)

print(setting1, setting2)

The print(setting1, setting2) doesn't work. I take a look at the PyYAML documentation but am unable to find it.


Solution

  • I am not sure if what you want to do is a good idea, but it can be achieved by assigning to globals(). Assuming the document containing your YAML file contains a root level mapping:

    from pathlib import Path
    import ruamel.yaml
    
    file_in = Path('settings.yaml')
    
        
    yaml = ruamel.yaml.YAML()
    data = yaml.load(file_in)
    for k, v in data.items():
        globals()[k] = v
    
    print(setting1, setting2)
    

    which gives:

    cat dog
    

    The officially recommended extension for files containing YAML documents has been .yaml, since at least September 2006