28

While dumping/serializing data having long lines in input, pyyaml adds extra indentation with new line - which is annoying, how can we avoid this conversion in two lines / multiple lines ?

e.g.

In [1]:

x = "-c /home/user/test/test2/test23/tet/2s/test1/stest/longdirectory1/directory2/ --optnion12 --verbose"

In [2]: import yaml

In [3]: print (yaml.dump([dict(ATTRIBUTES=[dict(CONFIG=x)])], default_flow_style=False))

WRONG ONE

- ATTRIBUTES:
  - CONFIG: -c /home/user/test/test2/test23/tet/2s/test1/stest/longdirectory1/directory2/
      --optnion12 --verbose

Which should be like

- ATTRIBUTES:
  - CONFIG: -c /home/user/test/test2/test23/tet/2s/test1/stest/longdirectory1/directory2/ --optnion12 --verbose
shahjapan
  • 12,609
  • 22
  • 69
  • 100

1 Answers1

45

Thanks @MathieuMarques for suggesting to look @ dump options and link provided, YAML documentation was not good enough to find it out.

Anyways solution is to specify width parameter for dump function.

i.e. yaml.dump(data, width=1000)

A better approach suggested by @RandomCoder to use yaml.dump(data, width=float("inf")) for a permanent solution.

shahjapan
  • 12,609
  • 22
  • 69
  • 100
  • 22
    More permanent solution is :`yaml.dump(data, width=float("inf"))` – RandomCoder May 14 '16 at 22:57
  • _However_, you can't use `width=float("inf")` when using the faster C-based (LibYAML) dumpers (e.g. `Dumper=yaml.CSafeDumper`). In that case something like `width=2147483647` should suffice. – pallgeuer Jul 15 '20 at 19:04
  • 1
    Alternatively you can probably use [`width=math.inf`](https://stackoverflow.com/a/30157018/1321680) which may be more readable than `float("inf")` (you need to `import math`). – patryk.beza Jul 26 '21 at 09:40