【问题标题】:How do you add a type tag when using a PyYAML dumper?使用 PyYAML 转储程序时如何添加类型标签?
【发布时间】:2016-07-18 20:36:32
【问题描述】:

我有一个简单的数据结构,我需要将其转储到 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)

【问题讨论】:

    标签: python yaml pyyaml


    【解决方案1】:

    如果我正确阅读了您的!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() 加载此内容时,您的加载程序希望找到constructor!v2 标记类型,除非您在实际加载例程之外阅读第一行。


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 2022-10-12
      • 2021-11-30
      • 1970-01-01
      • 2014-01-15
      • 2021-05-20
      相关资源
      最近更新 更多