Ruyaml: Possible to define line width?

Viewed 92

Is it possible to set YAML line width, when dumping to file with ruyaml?

When dumping a YAML object to file with pyyaml and its content is fairly long 82+(or something similar) characters, there is a row break inserted. This can be circumvented by giving the parameter "width" to the dump function, where you can either give a specific length or as in the example below "inf".

That possibility seems to be missing in ruyaml.

Traceback (most recent call last):
  File "/home/anton/work/repos/identityhub/bug.py", line 19, in <module>
    ruamel.dump(ruamel_content, ruamel_out.open("w"), width=float("inf"))
TypeError: dump() got an unexpected keyword argument 'width'

PS. Also added ruamel.yaml example, to verify that it is not an issue in the ruyaml fork.

from pathlib import Path
from ruyaml import YAML as RUYAML
from ruamel.yaml import YAML as RUAMEL
import yaml

ruyaml = RUYAML()
ruamel = RUAMEL()
ruyaml.indent(mapping=2, sequence=4, offset=2)

file_path = Path("test.yaml")
ruyaml_out = Path("ruyaml.yaml")
ruamel_out = Path("ruamel.yaml")
yaml_out = Path("yaml.yaml")

ruyaml_content = ruyaml.load(file_path)
ruyaml.dump(ruyaml_content, ruyaml_out.open("w"))

ruamel_content = ruamel.load(file_path)
ruamel.dump(ruamel_content, ruamel_out.open("w"))

yaml_content = yaml.load(file_path.open())
yaml.dump(yaml_content, yaml_out.open("w"), width=float("inf"))

Sample YAML to see the effect:

Foo:
  Bar: A very long string A very long string A very long string A very long string A
2 Answers

You should use:

yaml = YAML()
yaml.width = 2 ** 32

Although float("inf") > 2 gives True, and the yaml.width value is currently used for comparison, I cannot guarantee that at some point the internal code needs an actual integer. And since doing int(float"inf")) will give you

OverflowError: cannot convert float infinity to integer

your code would no longer work unless the conversion to int caught that exception.

Stumbled upon the "width" member variable on the YAML instance, seems to have the same effect as sending width=X to PyYaml dump function.

yaml = YAML()
yaml.width = float("inf")
Related