yaml - 使用 PyYAML.dump() 生成 anchor ?

标签 yaml pyyaml cross-reference

我希望能够在 PyYAML 的 dump() 函数生成的 YAML 中生成 anchor 。有没有办法做到这一点?理想情况下, anchor 与 YAML 节点具有相同的名称。

例子:

import yaml
yaml.dump({'a': [1,2,3]})
'a: [1, 2, 3]\n'

我希望能够做的是生成 YAML,如:
import yaml
yaml.dump({'a': [1,2,3]})
'a: &a [1, 2, 3]\n'

我可以编写自定义发射器或转储器来执行此操作吗?还有其他方法吗?

最佳答案

默认情况下,只有在检测到对先前看到的对象的引用时才会发出 anchor :

>>> 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

如果你想覆盖它的命名方式,你必须自定义 Dumper class ,特别是 generate_anchor()功能。 ANCHOR_TEMPLATE也可能有用。

在您的示例中,节点名称很简单,但您需要考虑 YAML 值的多种可能性,即它可能是一个序列而不是单个值:
>>> 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

关于yaml - 使用 PyYAML.dump() 生成 anchor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18065427/

相关文章:

python-sphinx - 在Sphinx中的引用内保留内联代码

python - 我不喜欢 "yaml.dump()"保存文件的方式。还有其他选择吗?

java - 合并来自 starter 和 spring-boot 应用程序的 2 个文件

Azure-DevOps:Azure Pipeline 中的自动增量 docker 标签

Python yaml 按原样转储表情符号

latex - 通过 rmarkdown 交叉引用章节编号或名称

java - 无法为标签 :yaml. org,2002 构造 java 对象

Cygwin - 如何安装ansible?

python - python的YAML输出格式

python - :func: and :meth: roles in Python Sphinx? 之间的行为有什么区别