0

I have a configuration file and would like to create a Config class that has attributes for the different sections and values in the config file.

For example, I have a yaml file (though json would also be fine), set up like this:

section1:
    key1: value1
    key2: value2

section2:
    key1: value1

I would like to be able to retrieve attributes by calling the class like so: Config.section1.key1

There might be a need to add to this file in the future, so I would like to be able to update the Config class with any additional elements in the yaml file.

I can successfully assign the section name to an instantiated object with the following:

class Config(object):
    def __init__(self):
        with open("config.yml", 'r') as ymlfile:
            cfg = yaml.load(ymlfile)

        for section in cfg.items():
            setattr(self, section[0], section[1])

This allows the following to work just fine:

config = Config()
print(config.section1)

But I cannot do the same for the Config class itself.

I also cannot figure out how to store the nested attributes. I've tried this:

for section in cfg.items():
    setattr(self, section[0], section[1])
    for key in section[1]:
        setattr(section, key, section[1][key])

But it just return the following error:

Traceback (most recent call last):
  File "config_so.py", line 13, in <module>
    config = Config()
  File "config_so.py", line 12, in __init__
    setattr(section, key, section[1][key])
AttributeError: 'tuple' object has no attribute 'server'
Bianchi
  • 138
  • 1
  • 2
  • 7
  • `section` is a local (tuple-valued) variable in your `__init__` method, not an attribute of the `Config` instance. – chepner Oct 20 '17 at 17:30
  • @chepner OK. Maybe I have the terminology a little off. I did write: "I can successfully assign the section name to an instantiated object"... "But I cannot do the same for the Config class itself". What would be a better way of phrasing it? – Bianchi Oct 20 '17 at 17:33
  • I'd read over https://stackoverflow.com/q/4984647/1126841, because you are essentially asking how to treat `dict` keys as attributes. The fact that the source of the `dict` is a YAML file isn't really relevant. – chepner Oct 20 '17 at 17:42

0 Answers0