I want to load some YAML data in a Python script, but instead of using regular dict
for mapping, I would like to use my custom class (which keeps the insertion order and also merges keys/subdictionaries instead of overwriting them). I don't want to alter any other YAML types, only mapping. Browsing through the net, pyyaml documentation and SO I don't see any clear an generic solution - in almost all cases undocumented features of pyyaml are used (for example most of the solutions here). Initially I was thinking about inheriting from yaml.Loader
and reimplementing construct_mapping()
, but it seems that it would also require to use some of pyyaml internals... But maybe it would "just work" when done like this:
# in my custom loader
def construct_mapping(self, node, deep=False):
mapping = yaml.Loader.construct_mapping(self, node, deep)
# do my own stuff with mapping, changing it to my own type
return mapping
?
Maybe I should just add my custom constructor and use !!map
as the YAML tag which will be matched? Will this work that way, even though typically mapping has no explicit tag in YAML file?
Am I missing some obvious solution here, or maybe reimplementing construct_mapping()
is the easiest approach?