首页 > 解决方案 > Python Ruamel YAML 使用别名和合并键加载注释

问题描述

Ruamel 似乎不会在别名扩展期间使用合并键复制注释(它使用常规锚点),至少在默认情况下是这样。有没有办法做到这一点?

示例:如果我加载此示例 YAML 文件:

aliases:
  - &a1
    b1: 5         # Comment for b1=5
    c1: 3         # Comment for c1=3

model:
  obj1:
    <<: *a1
    d1: 7         # Comment for d1=7
  obj2:
    *a1
  obj3:
    *a1

使用此代码:

import ruamel.yaml as yaml

with open("test.yaml") as fp:
    d = yaml.load(fp, yaml.RoundTripLoader)

def showcmts(d):
    for k,v in d.items():
        print("Key {} has {}".format(k, (d.ca.items[k][2] if k in d.ca.items and d.ca.items[k][2] is not None else "no comment")))

print("Model obj1 contents and comments are:")
showcmts(d["model"]["obj1"])
print("Model obj2 contents and comments are:")
showcmts(d["model"]["obj2"])
print("Model obj3 contents and comments are:")
showcmts(d["model"]["obj3"])

我得到这个输出:

Model obj1 contents and comments are:
Key d1 has CommentToken('# Comment for d1=7\n', line: 8, col: 18)
Key b1 has no comment
Key c1 has no comment
Model obj2 contents and comments are:
Key b1 has CommentToken('# Comment for b1=5\n', line: 2, col: 18)
Key c1 has CommentToken('# Comment for c1=3\n\n', line: 3, col: 18)
Model obj3 contents and comments are:
Key b1 has CommentToken('# Comment for b1=5\n', line: 2, col: 18)
Key c1 has CommentToken('# Comment for c1=3\n\n', line: 3, col: 18)

注释已经为锚加载,如果有多个(我用 obj3 做的测试),确实会复制,但不是合并(我需要它为我正在处理的项目做)。

想法?漏洞?

谢谢

标签: yamlruamel.yaml

解决方案


推荐阅读