Reading YAML config file in python and using variables

后端 未结 2 509
栀梦
栀梦 2020-12-11 03: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

2条回答
  •  半阙折子戏
    2020-12-11 04:01

    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.

提交回复
热议问题