在PyYAML中格式化自定义类输出

时间:2014-11-04 21:01:43

标签: python yaml pyyaml

我在这里做了一个简单的例子,但是文档仍然让我有些困惑。
以下是示例代码:

class A(yaml.YAMLObject):
    yaml_tag = u'!A'

    def __init__(self, val):
        self.val = val

if __name__ == '__main__':
    t = datetime.time()
    a = A(t)
    print yaml.dump(a)
    print yaml.load(yaml.dump(a)).val == t

输出

  

!一个val:!! python / object / apply:datetime.time [" \ 0 \ 0 \ 0 \ 0 \ 0 \ 0"]

     

因此,它似乎是忠实的d- /序列化,但默认的时间对象格式留下了一些需要。如何在保留我强大的转储/装载能力的同时让它更漂亮?

由于

1 个答案:

答案 0 :(得分:11)

重新定义文档中所有时间的时间格式

您可以使用PyYAML 'representers' and 'constructors'为文档中的任何datetime.time个实例定义自己的序列化格式。

import datetime

import yaml

time_format = '%H:%M:%S'


def time_representer(dumper, data):
    return dumper.represent_scalar(u'!time', data.strftime(time_format))


def time_constructor(loader, node):
    value = loader.construct_scalar(node)
    return datetime.datetime.strptime(value, time_format).time()


yaml.add_representer(datetime.time, time_representer)
yaml.add_constructor(u'!time', time_constructor)


class A(yaml.YAMLObject):
    yaml_tag = u'!A'

    def __init__(self, val):
        self.val = val


if __name__ == '__main__':
    t = datetime.time()
    a = A(t)
    print yaml.dump(a, default_flow_style=False)
    print yaml.load(yaml.dump(a)).val == t

将输出:

!A
val: !time '00:00:00'

True

仅为特定类重新定义时间格式

您还可以定义特定类如何序列化和反序列化。这样您就可以只更改A的时间表示方式。 Docs for YAMLObject

import datetime

import yaml

time_format = '%H:%M:%S'

class A(yaml.YAMLObject):
    yaml_tag = u'!A'

    def __init__(self, val):
        self.val = val

    @classmethod
    def to_yaml(cls, dumper, data):
        dict_representation = {
            'val':data.val.strftime(time_format)
        }
        node = dumper.represent_mapping(u'!A', dict_representation)
        return node

    @classmethod
    def from_yaml(cls, loader, node):
        dict_representation = loader.construct_mapping(node)
        val = datetime.datetime.strptime(
            dict_representation['val'], time_format).time()
        return A(val)

if __name__ == '__main__':
    t = datetime.time()
    a = A(t)
    print yaml.dump([t,a], default_flow_style=False)

    loaded = yaml.load(yaml.dump([t,a]))
    print loaded[0] == t
    print loaded[1].val == t

将输出:

- !!python/object/apply:datetime.time
  - "\0\0\0\0\0\0"
- !A
  val: 00:00:00

True
True