【发布时间】:2020-10-15 20:20:27
【问题描述】:
我正在创建一个自定义 yaml 标签 MyTag。它可以包含任何给定的有效 yaml - 映射、标量、锚点、序列等。
如何实现 MyTag 类来对此标签进行建模,以便 ruamel 以与解析任何给定 yaml 完全相同的方式解析 !mytag 的内容? MyTag 实例只存储 yaml 内容的解析结果。
以下代码有效,并且断言应该准确地演示它应该做什么并且它们都通过了。
但我不确定它是否出于正确的原因工作。 . .特别是在from_yaml 类方法中,使用commented_obj = constructor.construct_undefined(node) 是一种推荐的实现方式,并且从产生的生成器中消耗1 且仅1 正确吗?这不是偶然的吗?
我应该改用construct_object 或construct_map 之类的东西吗? . .?我能够找到的示例倾向于知道它正在构造什么类型,因此可以使用construct_map 或construct_sequence 来选择要构造的对象类型。在这种情况下,我实际上想为可能存在的任何未知类型搭载通常/标准的 ruamel 解析,并将其存储在自己的类型中。
import ruamel.yaml
from ruamel.yaml.comments import CommentedMap, CommentedSeq, TaggedScalar
class MyTag():
yaml_tag = '!mytag'
def __init__(self, value):
self.value = value
@classmethod
def from_yaml(cls, constructor, node):
commented_obj = constructor.construct_undefined(node)
flag = False
for data in commented_obj:
if flag:
raise AssertionError('should only be 1 thing in generator??')
flag = True
return cls(data)
with open('mytag-sample.yaml') as yaml_file:
yaml_parser = ruamel.yaml.YAML()
yaml_parser.register_class(MyTag)
yaml = yaml_parser.load(yaml_file)
custom_tag_with_list = yaml['root'][0]['arb']['k2']
assert type(custom_tag_with_list) is MyTag
assert type(custom_tag_with_list.value) is CommentedSeq
print(custom_tag_with_list.value)
standard_list = yaml['root'][0]['arb']['k3']
assert type(standard_list) is CommentedSeq
assert standard_list == custom_tag_with_list.value
custom_tag_with_map = yaml['root'][1]['arb']
assert type(custom_tag_with_map) is MyTag
assert type(custom_tag_with_map.value) is CommentedMap
print(custom_tag_with_map.value)
standard_map = yaml['root'][1]['arb_no_tag']
assert type(standard_map) is CommentedMap
assert standard_map == custom_tag_with_map.value
custom_tag_scalar = yaml['root'][2]
assert type(custom_tag_scalar) is MyTag
assert type(custom_tag_scalar.value) is TaggedScalar
standard_tag_scalar = yaml['root'][3]
assert type(standard_tag_scalar) is str
assert standard_tag_scalar == str(custom_tag_scalar.value)
还有一些示例 yaml:
root:
- item: blah
arb:
k1: v1
k2: !mytag
- one
- two
- three-k1: three-v1
three-k2: three-v2
three-k3: 123 # arb comment
three-k4:
- a
- b
- True
k3:
- one
- two
- three-k1: three-v1
three-k2: three-v2
three-k3: 123 # arb comment
three-k4:
- a
- b
- True
- item: argh
arb: !mytag
k1: v1
k2: 123
# blah line 1
# blah line 2
k3:
k31: v31
k32:
- False
- string here
- 321
arb_no_tag:
k1: v1
k2: 123
# blah line 1
# blah line 2
k3:
k31: v31
k32:
- False
- string here
- 321
- !mytag plain scalar
- plain scalar
- item: no comment
arb:
- one1
- two2
【问题讨论】:
标签: yaml ruamel.yaml