简体   繁体   中英

why the ruamel.yaml automatically add anchors and aliases?

I have one question about ruamel.yaml, There is my code as below,

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

my expect result is

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

but I got the format below, that contains anchor and aliases. How can I make it not create an anchor and aliases?

  - 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

Aliases are the way YAML can dump shared data, in your case the list/sequence ['flat']

The anchor and aliases mechanism is necessary to be able to dump recursive data structures, ie ones that are directory or indirectly self-referential, like:

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

The above is something that simple serializing language, such as JSON, cannot deal with.

Since you just have a shared data structure that is not self-referential, you can either assing copies:

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

or tell the representer to ignore aliases:

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)

which gives:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM