Search code examples
pythonpython-3.xyamlpyyaml

Import YAML variables automatically?


I've provided the code below. I'm just wondering if there's a better, more concise, way to load the entire index into variables, instead of manually specifying each one...

Python code

script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, 'config.yaml')

with open(file_path, 'r') as stream:
    index = 'two'
    load = yaml.load(stream)
    USER = load[index]['USER']
    PASS = load[index]['PASS']
    HOST = load[index]['HOST']
    PORT = load[index]['PORT']
    ...

YAML Config

one:
  USER: "john"
  PASS: "qwerty"
  HOST: "127.0.0.1"
  PORT: "20"
two:
  USER: "jane"
  PASS: "qwerty"
  HOST: "196.162.0.1"
  PORT: "80"

Solution

  • Assing to globals():

    import yaml
    import os
    
    script_dir = os.path.dirname(__file__)
    file_path = os.path.join(script_dir, 'config.yaml')
    
    index = 'two'
    
    with open(file_path, 'r') as stream:
        load = yaml.safe_load(stream)
    
    for key in load[index]:
        globals()[str(key)] = load[index][key]
    
    print(USER)
    print(PORT)
    

    this gives:

    jane
    80
    

    A few notes:

    • Using global variables is often considered bad practise
    • As noted by a p in the comment, this can lead to problems e.g. with keys that shadow built-ins
    • If you have to use PyYAML, you should use safe_load().
    • You should consider using ruamel.yaml (disclaimer: I am the author of that package), where you can get the same result with:

      import ruamel.yaml
      yaml = ruamel.yaml.YAML(typ='safe')
      

      and then again use load = yaml.load(stream) (which is safe).