Python 使用PyYAML转储程序时如何添加类型标记?
我有一个简单的数据结构,我需要将其转储到YAML文件中,并在开头添加一个类型标记,标记为Python 使用PyYAML转储程序时如何添加类型标记?,python,yaml,pyyaml,Python,Yaml,Pyyaml,我有一个简单的数据结构,我需要将其转储到YAML文件中,并在开头添加一个类型标记,标记为!v2行 我如何使用PyYAML库来实现这一点 import yaml class MyDumper(yaml.SafeDumper): # ??? # somehow add a "!v2" type tag at the beginning y = {'foo': 3, 'bar': 'haha', 'baz': [1,2,3]} with open(myfile, 'w') as
!v2
行
我如何使用PyYAML库来实现这一点
import yaml
class MyDumper(yaml.SafeDumper):
# ???
# somehow add a "!v2" type tag at the beginning
y = {'foo': 3, 'bar': 'haha', 'baz': [1,2,3]}
with open(myfile, 'w') as f:
# a hack would be to write the "!v2" here,
# outside the normal yaml.dump process,
# but I'd like to learn the right way
yaml.dump(f, y, Dumper=MyDumper)
如果我读了你的
!v2
正确添加这本质上是顶级字典的标记(因此对整个文件是隐式的)。为了正确地用标记将其写出,请将该顶级dict转换为单独的类型(从dict子类化),并创建特定于类型的转储程序:
import ruamel.yaml as yaml
from ruamel.yaml.representer import RoundTripRepresenter
class VersionedDict(dict):
pass
y = VersionedDict(foo=3, bar='haha', baz=[1,2,3])
def vdict_representer(dumper, data):
return dumper.represent_mapping('!v2', dict(data))
RoundTripRepresenter.add_representer(VersionedDict, vdict_representer)
print(yaml.round_trip_dump(y))
将为您提供:
!v2
bar: haha
foo: 3
baz:
- 1
- 2
- 3
往返转储
是一个安全转储
请注意,当您以某种方式使用yaml.load()
加载此文件时,您的加载程序希望为找到一个构造函数!v2
标记类型,除非您读取实际加载例程之外的第一行
以上是用(我是作者)PyYAML的增强版完成的。如果您必须坚持使用PyYAML(例如,如果您必须坚持使用YAML 1.1),那么您应该能够相对轻松地进行必要的更改。只需确保将representer添加到用于转储的representer:SafeRepresenter
使用safe\u dump
时