为什么 ruamel.yaml 会自动添加锚点和别名?

why the ruamel.yaml automatically add anchors and aliases?

我有一个关于 ruamel.yaml 的问题, 我的代码如下,

sriov_seg_type = ["flat"]
for port in sriov_port:
  port_dict = OrderedDict()
  port_dict["name"] = port
  port_dict["mtu"] = 9000
  port_dict["networkType"] = sriov_seg_type

我的预期结果是

 - name: P1
   mtu: 9000
   networkType:
     - flat
 - name: P2
   mtu: 9000
   networkType:
     - flat
 - name: P3
   mtu: 9000
   networkType:
     - flat
 - name: P4
   mtu: 9000
   networkType:
     - flat

但我得到了以下格式,其中包含锚点和别名。我怎样才能让它不创建锚点和别名?

  - name: P1
    mtu: 9000
    networkType: &id001
      - flat
  - name: P2
    mtu: 9000
    networkType: *id001
  - name: P3
    mtu: 9000
    networkType: *id001
  - name: P4
    mtu: 9000
    networkType: *id001

别名是 YAML 可以转储共享数据的方式,在您的情况下 list/sequence ['flat']

锚点和别名机制是转储递归数据所必需的 结构,即直接或间接自引用的结构,例如:

data = dict(a=1)
data['b'] = data

以上是JSON等简单的序列化语言无法处理的问题。

由于您只有一个非自引用的共享数据结构,您可以 分配副本:

    port_dict["networkType"] = sriov_seg_type.copy()

或告诉代表忽略别名:

import sys
import ruamel.yaml
from collections import OrderedDict

ruamel.yaml.representer.RoundTripRepresenter.ignore_aliases = lambda x, y: True

yaml = ruamel.yaml.YAML()


data = []
sriov_port = ['P1', 'P2', 'P3', 'P4']
sriov_seg_type = ["flat"]
for port in sriov_port:
  port_dict = dict()
  port_dict["name"] = port
  port_dict["mtu"] = 9000
  port_dict["networkType"] = sriov_seg_type
  data.append(port_dict)

yaml.dump(data, sys.stdout)

给出:

- name: P1
  mtu: 9000
  networkType:
  - flat
- name: P2
  mtu: 9000
  networkType:
  - flat
- name: P3
  mtu: 9000
  networkType:
  - flat
- name: P4
  mtu: 9000
  networkType:
  - flat