How can I ignore a member when serializing an object with PyYAML?

旧街凉风 提交于 2019-12-20 07:04:41

问题


How can ignore the member Trivial._ignore when serializing this object?

import yaml
class Trivial(yaml.YAMLObject):
    yaml_tag = u'!Trivial'
    def __init__(self):
        self.a = 1
        self.b = 2
        self._ignore = 3

t = Trivial()
print(yaml.dump(t))

prints

!Trivial
_ignore: 3
a: 1
b: 2

回答1:


def my_yaml_dump(yaml_obj):
    my_ob = deepcopy(yaml_obj)
    for item in dir(my_ob):
        if item.startswith("_") and not item.startswith("__"):
             del my_ob.__dict__[item]
    return yaml.dump(my_ob)

something like this would ignore anything with a single (leading) underscore

I think this is what you want

class Trivial(yaml.YAMLObject):
    yaml_tag = u'!Trivial'
    def __init__(self):
        self.a = 1
        self.b = 2
        self._ignore = 3
    @classmethod
    def to_yaml(cls, dumper, data):
        # ...
        my_ob = deepcopy(data)
        for item in dir(my_ob):
            if item.startswith("_") and not item.startswith("__"):
                del my_ob.__dict__[item]
        return dumper.represent_yaml_object(cls.yaml_tag, my_ob, cls,
                                                flow_style=cls.yaml_flow_style)

although a better method (stylistically)

class SecretYamlObject(yaml.YAMLObject):
     hidden_fields = []
     @classmethod
     def to_yaml(cls,dumper,data):
         new_data = deepcopy(data)
         for item in cls.hidden_fields:
             del new_data.__dict__[item]
         return dumper.represent_yaml_object(cls.yaml_tag, new_data, cls,
                                            flow_style=cls.yaml_flow_style)

class Trivial(SecretYamlObject):
     hidden_fields = ["_ignore"]
     yaml_tag = u'!Trivial'
     def __init__(self):
        self.a = 1
        self.b = 2
        self._ignore = 3

print yaml.dump(Trivial())

this is adhering to pythons mantra of explicit is better than implicit



来源:https://stackoverflow.com/questions/22773612/how-can-i-ignore-a-member-when-serializing-an-object-with-pyyaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!