Skip to content Skip to sidebar Skip to footer

How Can I Ignore A Member When Serializing An Object With Pyyaml?

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.

Solution 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

classTrivial(yaml.YAMLObject):
    yaml_tag = u'!Trivial'def__init__(self):
        self.a = 1
        self.b = 2
        self._ignore = 3    @classmethoddefto_yaml(cls, dumper, data):
        # ...
        my_ob = deepcopy(data)
        for item indir(my_ob):
            if item.startswith("_") andnot 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)

classSecretYamlObject(yaml.YAMLObject):
     hidden_fields = []
     @classmethoddefto_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)

classTrivial(SecretYamlObject):
     hidden_fields = ["_ignore"]
     yaml_tag = u'!Trivial'def__init__(self):
        self.a = 1
        self.b = 2
        self._ignore = 3print yaml.dump(Trivial())

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

Post a Comment for "How Can I Ignore A Member When Serializing An Object With Pyyaml?"