我正在尝试使用通过别名中的构造函数传递的锚定数据,但是别名想要使用预构造函数数据。
我从 anthon 的Is there a way to construction an object using PyYAML construction_mapping after all nodes complete loading? 中获得了灵感?但仍然没有找到快乐。
下面是一些示例代码:
class L2D(dict):
def __repr__(self):
return('L2D({})'.format(dict.__repr__(self)))
def l2d_constructor(loader, node):
print("constructing")
instance = L2D.__new__(L2D)
yield instance
state = loader.construct_sequence(node, deep=True)
instance.__init__(state)
yaml.add_constructor(u'!l2d', l2d_constructor)
print(yaml.load('''
a: !l2d
- [e, f]
- [g, h]
'''))
print("============")
print(yaml.load('''
a: &other !l2d
- [e, f]
- [g, h]
b:
<<: *other
a: b
c: d
'''))
第一个负载有效,但我希望第二个负载输出为
constructing
{'a': L2D({'g': 'h', 'e': 'f'}), 'b': {'a': 'b', 'g': 'h', 'e': 'f', 'c': 'd'}}
相反,我得到
constructing
Traceback (most recent call last):
File "test2.py", line 41, in <module>
'''))
File "/tmp/tmp.1oRXCix7X3/venv/lib/python3.5/site-packages/ruamel/yaml/main.py", line 86, in load
return loader.get_single_data()
File "/tmp/tmp.1oRXCix7X3/venv/lib/python3.5/site-packages/ruamel/yaml/constructor.py", line 56, in get_single_data
return self.construct_document(node)
File "/tmp/tmp.1oRXCix7X3/venv/lib/python3.5/site-packages/ruamel/yaml/constructor.py", line 65, in construct_document
for dummy in generator:
File "/tmp/tmp.1oRXCix7X3/venv/lib/python3.5/site-packages/ruamel/yaml/constructor.py", line 494, in construct_yaml_map
value = self.construct_mapping(node)
File "/tmp/tmp.1oRXCix7X3/venv/lib/python3.5/site-packages/ruamel/yaml/constructor.py", line 265, in construct_mapping
self.flatten_mapping(node)
File "/tmp/tmp.1oRXCix7X3/venv/lib/python3.5/site-packages/ruamel/yaml/constructor.py", line 240, in flatten_mapping
% subnode.id, subnode.start_mark)
ruamel.yaml.constructor.ConstructorError: while constructing a mapping
in "<unicode string>", line 8, column 3:
<<: *other
^ (line: 8)
expected a mapping for merging, but found sequence
in "<unicode string>", line 5, column 5:
- [e, f]
^ (line: 5)
打印结果constructing
表明构造函数已经完成了它的工作,但我怀疑它试图从未更改的 yaml 树中获取数据而不是从构造函数中获取结果数据的别名。
有什么办法可以使这项工作?