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'