使用 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 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添加,这本质上是顶级字典的标签(因此隐式用于整个文件(。为了用标签正确地写出来,将该顶级字典转换为单独的类型(从字典中子类化(并创建一个特定于类型的转储器:

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

roundtrip_dump是一个safe_dump

请注意,当您以某种方式使用 yaml.load() 加载此代码时,您的加载器希望找到 !v2 标记类型的constructor,除非您在实际加载例程之外读取第一行。


以上是用ruamel.yaml(我是作者(的PyYAML增强版本完成的,如果你必须坚持使用PyYAML(例如,如果你必须坚持使用YAML 1.1(,那么你应该能够相对容易地进行必要的更改。只需确保将表示器添加到用于转储的表示器:使用 safe_dumpSafeRepresenter

最新更新