是否可以在跨多个文档的多文档YAML流中使用别名?

时间:2016-11-20 08:13:53

标签: python yaml ruamel.yaml

这就是我尝试做的事情(代码在Python 3中):

import ruamel.yaml as yaml
from print import pprint

yaml_document_with_aliases = """
title: test
choices: &C
  a: one
  b: two
  c: three
---
title: test 2
choices: *C
"""

items = list(yaml.load_all(yaml_document_with_aliases))

结果是:

ComposerError: found undefined alias 'C'

当我使用非基于文档的YAML文件时,这可以按预期工作:

import ruamel.yaml as yaml
from print import pprint

yaml_nodes_with_aliases = """
-
  title: test
  choices: &C
    a: one
    b: two
    c: three
-
  title: test 2
  choices: *C
"""

items = yaml.load(yaml_nodes_with_aliases)

pprint(items)

结果:

[{'choices': {'a': 'one', 'b': 'two', 'c': 'three'}, 'title': 'test'},
 {'choices': {'a': 'one', 'b': 'two', 'c': 'three'}, 'title': 'test 2'}]

(我想要完成的任何事情)

由于现在不可能,我使用以下脆弱的解决方法:

def yaml_load_all_with_aliases(yaml_text):
    if not yaml_text.startswith('---'):
        yaml_text = '---\n' + yaml_text
    for pat, repl in [('^', '  '), ('^\s*---\s*$', '-'), ('^\s+\.{3}$\n', '')]:
        yaml_text = re.sub(pat, repl, yaml_text, flags=re.MULTILINE)
    yaml_text = yaml_text.strip()
    return yaml.safe_load(yaml_text)

1 个答案:

答案 0 :(得分:1)

这里的问题是:

title: test
choices: &C
  a: one
  b: two
  c: three
---
title: test 2
choices: *C

不是 文档,这是一个文件中的两个YAML文档。锚定义&C不会从一个YAML文档传送到另一个YAML文档,它只能在文档分隔符---之前用完。

如果您愿意在一个YAML流中将所有锚点“转移”到以下文档,您可以在compose_document类上移植一个新的Composer方法(即猴子补丁) :

import sys
import ruamel.yaml

yaml_str = """\
title: test
choices: &C
  a: one
  b: two
  c: three
---
title: test 2
choices: *C
"""


def my_compose_document(self):
    self.get_event()
    node = self.compose_node(None, None)
    self.get_event()
    # this prevents cleaning of anchors between documents in **one stream**
    # self.anchors = {}
    return node

ruamel.yaml.composer.Composer.compose_document = my_compose_document

datas = []
for data in ruamel.yaml.safe_load_all(yaml_str):
    datas.append(data)

datas[0]['choices']['a'] = 1
for data in datas:
    ruamel.yaml.round_trip_dump(data, sys.stdout, explicit_start=True)

给出:

---
title: test
choices:
  a: 1
  b: two
  c: three
---
title: test 2
choices:
  a: one
  b: two
  c: three

请注意,这会为您提供包含abc键的dict的副本

(如果密钥排序和评论保存很重要,请使用round_trip_load_all代替safe_load_all