我正在尝试使用通过别名中的构造函数传递的锚定数据,但是别名想要使用预构造函数数据。
我从安东的Is there a way to construct an object using PyYAML construct_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树获取数据的别名,而不是构造函数的结果数据。
有什么方法可以让我的工作吗?
答案 0 :(得分:0)
为了使用YAML的合并功能,您的锚定&#34;类型&#34;需要是一个映射(Python $stuff_request = 'https://thisdomain/api/stuff';
$username = 'thisdomainuser';
$password = 'thisdomainpassword';
$headers = array( 'Authorization' => 'Basic ' . base64_encode( "$username:$password" ) );
$stuff_response = wp_remote_get( $stuff_request, array( 'headers' => $headers));
if( is_array($stuff_response ) ) {
$header = $stuff_response['headers']; // array of http header lines
$body = json_decode( $stuff_response['body'] ); // use the content
}
),并且该映射的键/值对将插入到您执行的其他映射中:
dict
您的锚定类型是一个序列,使用合并功能时不允许这样做。
您应该查看merge documentation,您可以在其中看到锚定类型始终是映射。