Convert YAML multi-line values to folded block scalar style?
<p>Using <a href="https://yaml.readthedocs.io/" rel="nofollow noreferrer">ruamel.yaml</a> I tried to get a YAML in a certain style, more specifically one where single-line strings start at same line as <code>:</code> and multi-line strings using a folded scalar style (<code>|</code>/<code>|-</code>) and lines being limited to a certain amount of characters (word-wrapped).</p>

<p>My attempt so far heavily influenced by a <a href="https://bitbucket.org/ruamel/yaml/src/00c7352d22d00307ffa233b21d8a01a6ed6db4d0/scalarstring.py?fileviewer=file-view-default" rel="nofollow noreferrer">similar function called <code>walk_tree</code> in the sources</a>:
</p>

<pre><code>#!/usr/bin/env python

import ruamel.yaml

from ruamel.yaml.scalarstring import ScalarString, PreservedScalarString

def walk_tree(base):
    from ruamel.yaml.compat import string_types

    if isinstance(base, dict):
        for k in base:
            v = base[k]
            if isinstance(v, string_types):
                v = v.replace('\r\n', '\n').replace('\r', '\n').strip()
                base[k] = ScalarString(v) if '\n' in v else v
            else:
                walk_tree(v)
    elif isinstance(base, list):
        for idx, elem in enumerate(base):
            if isinstance(elem, string_types) and '\n' in elem:
                print(elem) # @Anthon: this print is in the original code as well
                base[idx] = preserve_literal(elem)
            else:
                walk_tree(elem)

with open("input.yaml", "r") as fi:
    inp = fi.read()

loader=ruamel.yaml.RoundTripLoader
data = ruamel.yaml.load(inp, loader)

walk_tree(data)

dumper = ruamel.yaml.RoundTripDumper

with open("output.yaml", "w") as fo:
    ruamel.yaml.dump(data, fo, Dumper=dumper, allow_unicode=True)
</code></pre>

<p>But then I get an exception: <code>ruamel.yaml.representer.RepresenterError: cannot represent an object: …</code>. I get no exception if I replace <code>ScalarString</code> with <code>PreservedScalarString</code> as is the case in the original <code>walk_tree</code> code but then I get the literal blocks again which is not what I want.</p>

<p>So how can my code be fixed so that it will work? </p>