So I have this class:
import yaml
class Config():
def __init__(self, filename):
self.config_filename=filename
def __read_config_file(self):
with open(self.config_filename) as f:
self.cfg = yaml.safe_load(f)
def get(self):
self.__read_config_file()
return self.cfg
And it works fine. The thought behind it is to force a reread of the config file every time I use something in the configuration. Here is an example of usage:
cfg = Config('myconfig.yaml')
for name in cfg.get()['persons']:
print (cfg.get()['persons'][name]['phone'])
print (cfg.get()['persons'][name]['address'])
This works, but I think it looks extremely ugly. I could do something like this:
c = cfg.get()['persons']
for name in c:
print (c['persons'][name]['phone'])
print (c['persons'][name]['address'])
Which looks just a tiny bit better, but I also lose the benefit of reloading on access, but what I want to do is something this (which obviously does not work):
for name in c:
print (name['phone'])
print (name['address'])
It seems like it's something I don't understand about iterating over dictionaries, but my main concern here is that I want to reload the configuration file each time any value from that file is used, and I want it in a nice readable way. So how can I redesign this?
Example of configuration file. It's possible to change the format here if necessary.
persons:
john:
address: "street A"
phone: "123"
george:
address: "street B"
phone: "456"