Search code examples
python-3.xpyyamlruamel.yaml

Transform attribute in yaml.dump is not working


If we want to alter the output of yaml.dump we can use tranform keyword argument. Documentation: https://yaml.readthedocs.io/en/latest/example.html

Here is the yaml data:

metadata:
  name: name
  alias: alias

it is stored in variable x.

x = 'metadata:\n  name: name\n  alias: alias\n'

def tr(s):
    return s.replace('\n', '\n    ')  # Want 4 space at each new line

from ruamel.yaml import YAML
from ruamel.yaml.compat import StringIO

yaml = YAML(typ="safe")
yaml.default_flow_style = False
stream = StringIO()

obj = yaml.load(x)
yaml.dump(obj, stream, transform=tr)
print(stream.getvalue())

On running above python script, Got this error: TypeError: a bytes-like object is required, not 'str'

Expected output:

    metadata:
      name: name
      alias: alias

Note: Another 4 spaces are added in each line

Version Details of setup:

Python: 3.7
ruamel.yaml: 0.15.88

Solution

  • The problem only happens with StringIO, because YAML() always sets the encoding to utf-8 (and allow_unicode = True).

    Changing to use io didn't help. If you want to write to StringIO in python2.7 you'll have to disable the utf-8 encoding:

    i.e.

    yaml = YAML(typ="safe")
    yaml.default_flow_style = False
    stream = StringIO()
    yaml.encoding = None
    

    For more info see this ticket : https://sourceforge.net/p/ruamel-yaml/tickets/271/