使用 PyYAML.dump() 生成锚点? [英] Generating anchors with PyYAML.dump()?
问题描述
我希望能够在 PyYAML 的 dump() 函数生成的 YAML 中生成锚点.有没有办法做到这一点?理想情况下,锚点应与 YAML 节点同名.
示例:
导入yamlyaml.dump({'a': [1,2,3]})'a: [1, 2, 3]\n'
我希望能够做的是生成 YAML,例如:
导入yamlyaml.dump({'a': [1,2,3]})'a: &a [1, 2, 3]\n'
我可以编写自定义发射器或转储器来执行此操作吗?还有别的方法吗?
默认情况下,只有在检测到对先前看到的对象的引用时才会发出锚点:
<预><代码>>>>导入 yaml>>>>>>foo = {'a': [1,2,3]}>>>文档 = (foo,foo)>>>>>>打印 yaml.safe_dump(doc, default_flow_style=False)- &id001A:- 1- 2- 3- *id001如果您想覆盖它的命名方式,您必须自定义 Dumper 类,特别是 generate_anchor()
函数.ANCHOR_TEMPLATE
也可能有用.
在您的示例中,节点名称很简单,但您需要考虑 YAML 值的多种可能性,即它可能是一个序列而不是单个值:
<预><代码>>>>导入 yaml>>>>>>foo = {('a', 'b', 'c'): [1,2,3]}>>>文档 = (foo,foo)>>>>>>打印 yaml.dump(doc, default_flow_style=False)!!蟒蛇/元组- &id001?!!蟒蛇/元组- 一种- 乙- C: - 1- 2- 3- *id001I'd like to be able to generate anchors in the YAML generated by PyYAML's dump() function. Is there a way to do this? Ideally the anchors would have the same name as the YAML nodes.
Example:
import yaml
yaml.dump({'a': [1,2,3]})
'a: [1, 2, 3]\n'
What I'd like to be able to do is generate YAML like:
import yaml
yaml.dump({'a': [1,2,3]})
'a: &a [1, 2, 3]\n'
Can I write a custom emitter or dumper to do this? Is there another way?
By default, anchors are only emitted when it detects a reference to an object previously seen:
>>> import yaml
>>>
>>> foo = {'a': [1,2,3]}
>>> doc = (foo,foo)
>>>
>>> print yaml.safe_dump(doc, default_flow_style=False)
- &id001
a:
- 1
- 2
- 3
- *id001
If you want to override how it is named, you'll have to customize the Dumper class, specifically the generate_anchor()
function. ANCHOR_TEMPLATE
may also be useful.
In your example, the node name is simple, but you need to take into account the many possibilities for YAML values, ie it could be a sequence rather than a single value:
>>> import yaml
>>>
>>> foo = {('a', 'b', 'c'): [1,2,3]}
>>> doc = (foo,foo)
>>>
>>> print yaml.dump(doc, default_flow_style=False)
!!python/tuple
- &id001
? !!python/tuple
- a
- b
- c
: - 1
- 2
- 3
- *id001
这篇关于使用 PyYAML.dump() 生成锚点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!