14

Say I have a yaml config file such as:

test1:
    minVolt: -1
    maxVolt: 1
test2:
    curr: 5
    volt: 5

I can read the file into python using:

import yaml

with open("config.yaml", "r") as f:
    config = yaml.load(f)

Then I can access the variables with

config['test1']['minVolt']

Style-wise, what is the best way to use variables from the config file? I will be using the variables in multiple modules. If I simply access the variables as shown above, if something is renamed, I will need to rename every instance of the variable.

Just wondering what the best or common practices for using variables from a config file in different modules.

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
camerausb
  • 163
  • 1
  • 1
  • 9

2 Answers2

9

You can do this:

class Test1Class:
    def __init__(self, raw):
        self.minVolt = raw['minVolt']
        self.maxVolt = raw['maxVolt']

class Test2Class:
    def __init__(self, raw):
        self.curr = raw['curr']
        self.volt = raw['volt']

class Config:
    def __init__(self, raw):
        self.test1 = Test1Class(raw['test1'])
        self.test2 = Test2Class(raw['test2'])

config = Config(yaml.safe_load("""
test1:
    minVolt: -1
    maxVolt: 1
test2:
    curr: 5
    volt: 5
"""))

And then access your values with:

config.test1.minVolt

When you rename the values in the YAML file, you only need to change the classes at one place.

Note: PyYaml also allows you to directly deserialize YAML to custom classes. However, for that to work, you'd need to add tags to your YAML file so that PyYaml knows which classes to deserialize to. I expect that you do not want to make your YAML input more complex.

flyx
  • 35,506
  • 7
  • 89
  • 126
  • Another question, for when using a GUI interface. I have a tab with configuration settings where the user is able to edit the config file. I am able to overwrite the yaml config file, but when accessing the variables in another module (after the variables have been updated), the module still uses the original values. Only after I exit out of the GUI and restart the program, does it use the new values. Why is this and how can I fix it? – camerausb Aug 04 '16 at 01:21
  • If this answer solves your problem, please mark it as such. If you have another problem, create a new question showing your code and describing your problem instead of commenting here. – flyx Aug 04 '16 at 08:36
1

See Munch, Load YAML as nested objects instead of dictionary in Python

import yaml
from munch import munchify
c = munchify(f)yaml.safe_load(…))
print(c.test1.minVolt)
# -1
# Or
f = open(…)
c = Munch.fromYAML(f)
Hans Ginzel
  • 8,192
  • 3
  • 24
  • 22