def __init__(self, **options):
super(YamlReaderWriter, self).__init__(**options)
try:
import yaml
import yaml.resolver
except ImportError:
raise RuntimeError('To use YAML, please install PyYAML first')
#
# The code to preserve order of items is taken from here:
# https://stackoverflow.com/a/21048064/38611
#
_mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
def dict_representer(dumper, data):
return dumper.represent_dict(data.items())
def dict_constructor(loader, node):
return collections.OrderedDict(loader.construct_pairs(node))
yaml.add_representer(collections.OrderedDict, dict_representer)
yaml.add_constructor(_mapping_tag, dict_constructor)
self.yaml = yaml
self.default_dump_options = {
'indent': 2,
'default_flow_style': False,
}