如何使用 ruamel.yaml 正确缩进序列?

How get the sequences properly indented with ruamel.yaml?

有以下数据

from ruamel import yaml
data = {1: {1:[{1:1,2:2},{1:1,2:2}], 2:2}, 2: 42}

我得到的序列缩进不正确

>>> print yaml.round_trip_dump(data)
1:
  1:
  - 1: 1
    2: 2
  - 1: 1
    2: 2
  2: 2
2: 42

Notepad++无法折叠。然而,通过适当的缩进它可以工作:

差:

好:

我试过使用block_seq_indent=2:

>>> print yaml.round_trip_dump(data, block_seq_indent=2)
1:
  1:
    - 1: 1
    2: 2
    - 1: 1
    2: 2
  2: 2
2: 42

我该如何解决这个问题?

ruamel.yaml 文档虽然普遍缺乏,但对缩进内破折号的 offset 说了以下内容:

If the offset equals sequence, there is not enough room for the dash and the space that has to follow it. In that case the element itself would normally be pushed to the next line (and older versions of ruamel.yaml did so). But this is prevented from happening. However the indent level is what is used for calculating the cumulative indent for deeper levels and specifying sequence=3 resp. offset=2, might give correct, but counter intuitive results.

It is best to always have sequence >= offset + 2 but this is not enforced. Depending on your structure, not following this advice might lead to invalid output.

默认情况下 indent(对于映射和序列)等于 2,如果您这样做:

import sys
from ruamel import yaml

data = {1: {1:[{1:1,2:2},{1:1,2:2}], 2:2}, 2: 42}

yml = yaml.YAML()
yml.indent(mapping=2, sequence=4, offset=2)
yml.dump(data, sys.stdout)

你得到:

1:
  1:
    - 1: 1
      2: 2
    - 1: 1
      2: 2
  2: 2
2: 42

对于您在问题中使用的旧 API,您无法以微不足道的方式对映射和序列进行不同的缩进(您需要子 class 发射器,然后post __init__ 的基础 class,设置值)。对于旧版本的 ruamel.yaml 这根本不可能。

这仅适用于默认(往返,即 typ='rt')转储程序,但适用于正常的 Python dict resp。 list(例如来自 YAML(typ='safe').load(....))和 在做 YAML().load(....)

时使用了更多复杂的子classes

(以上要求ruamel.yaml>=0.15.30)