1

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"
Floern
  • 33,559
  • 24
  • 104
  • 119
J. Doe
  • 13
  • 1
  • 4
  • 1
    Possible duplicate of [Parsing a YAML file in Python, and accessing the data?](https://stackoverflow.com/questions/8127686/parsing-a-yaml-file-in-python-and-accessing-the-data) – Van Peer Oct 20 '17 at 05:26
  • Try using https://pyyaml.org/wiki/PyYAMLDocumentation – ayrusme Oct 20 '17 at 05:26
  • This provides an example of how I currently set up my code. In other words, I want the program to import all variables automatically. – J. Doe Oct 20 '17 at 05:55

1 Answers1

1

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).

Anthon
  • 69,918
  • 32
  • 186
  • 246
  • 1
    Note that this is potentially problematic since it will shadow builtins and things like True and False. – a p Oct 20 '17 at 05:59
  • Your answer was helpful! I'll check out your package as well. Thank you for responding : ) – J. Doe Oct 20 '17 at 06:11