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"
3

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Note that this is potentially problematic since it will shadow builtins and things like True and False.
Your answer was helpful! I'll check out your package as well. Thank you for responding : )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.