Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?

import yaml class folded_unicode(unicode): pass class literal_unicode(unicode): pass def folded_unicode_representer(dumper, data): return dumper.represent_scalar(u’tag:yaml.org,2002:str’, data, style=”>”) def literal_unicode_representer(dumper, data): return dumper.represent_scalar(u’tag:yaml.org,2002:str’, data, style=”|”) yaml.add_representer(folded_unicode, folded_unicode_representer) yaml.add_representer(literal_unicode, literal_unicode_representer) data = { ‘literal’:literal_unicode( u’by hjw ___\n’ ‘ __ /.-.\\\n’ ‘ / )_____________\\\\ Y\n’ ‘ /_ /=== == === === =\\ _\\_\n’ ‘( /)=== == === === == Y … Read more

How can I control what scalar form PyYAML uses for my data?

Falling in love with @lbt’s approach, I got this code: import yaml def str_presenter(dumper, data): if len(data.splitlines()) > 1: # check for multiline string return dumper.represent_scalar(‘tag:yaml.org,2002:str’, data, style=”|”) return dumper.represent_scalar(‘tag:yaml.org,2002:str’, data) yaml.add_representer(str, str_presenter) # to use with safe_dump: yaml.representer.SafeRepresenter.add_representer(str, str_presenter) It makes every multiline string be a block literal. I was trying to avoid the … Read more

PyYAML dump format

Below, ruamel.yaml is used instead. ruamel.yaml is actively maintained. Unlike PyYAML, ruamel.yaml supports: YAML <= 1.2. PyYAML only supports YAML <= 1.1. This is vital, as YAML 1.2 intentionally breaks backward compatibility with YAML 1.1 in several edge cases. This would usually be a bad thing. In this case, this renders YAML 1.2 a strict … Read more

Can PyYAML dump dict items in non-alphabetical order?

If you upgrade PyYAML to 5.1 version, now, it supports dump without sorting the keys like this: yaml.dump(data, sort_keys=False) As shown in help(yaml.Dumper), sort_keys defaults to True: Dumper(stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True) (These are passed as kwargs to yaml.dump)

In Python, how can you load YAML mappings as OrderedDicts?

Python >= 3.6 In python 3.6+, it seems that dict loading order is preserved by default without special dictionary types. The default Dumper, on the other hand, sorts dictionaries by key. Starting with pyyaml 5.1, you can turn this off by passing sort_keys=False: a = dict(zip(“unsorted”, “unsorted”)) s = yaml.safe_dump(a, sort_keys=False) b = yaml.safe_load(s) assert … Read more