I have an YAML config that looks like:
config:
- id: foo
- name: bar
content:
- run: xxx
- remove: yyy
I am using Python YAML module to load it but I want to access it in better ways like:
stream = open(filename)
config = load(stream, Loader=Loader)
print(config['content'])
What I want is to be able to do: print(config.content)
.
The easiest way to do this is probably to overwrite the YAML constructor for
tag:yaml.org,2002:map
so it returns a custom dictionary class instead of an ordinary dictionary.Note that this will break everything else in the process that uses YAML, if it expects everything to work the normal Python way. You can use a custom loader, but I personally find the PyYAML documentation a bit labyrinthine, and it seems that side effects are global and contagious as a rule rather than an exception.
You have been warned.
As an alternative, if your schema is relatively static you could write your own classes and deserialize to those (e.g.,
class Config
withid
andname
properties). It probably wouldn't be worth the cost of the extra code, however.You can use object notation with dictionaries using the following class, as discussed in this answer:
This class in action:
Edit This works recursively with sub-dictionaries, for example: