How to deserialize an object with PyYAML using safe_load?

前端 未结 3 671
攒了一身酷
攒了一身酷 2021-02-15 15:20

Having a snippet like this:

import yaml
class User(object):
    def __init__(self, name, surname):
       self.name= name
       self.surname= surname

user = U         


        
3条回答
  •  离开以前
    2021-02-15 15:39

    If you have many tags and don't want to create objects for all of them, or in case you don't care about the actual type returned, only about dotted access, you catch all undefined tags with the following code:

    import yaml
    
    class Blob(object):
        def update(self, kw):
            for k in kw:
                setattr(self, k, kw[k])
    
    from yaml.constructor import SafeConstructor
    
    def my_construct_undefined(self, node):
        data = Blob()
        yield data
        value = self.construct_mapping(node)
        data.update(value)
    
    SafeConstructor.add_constructor(None, my_construct_undefined)
    
    
    class User(object):
        def __init__(self, name, surname):
            self.name= name
            self.surname= surname
    
    user = User('spam', 'eggs')
    serialized_user = yaml.dump(user)
    #Network
    deserialized_user = yaml.safe_load(serialized_user)
    print "name: %s, sname: %s" % (deserialized_user.name, deserialized_user.surname)
    

    In case you wonder why the my_construct_undefined has a yield in the middle: that allows for instantiating the object separately from creation of its children. Once the object exist it can be referred to in case it has an anchor and of the children (or their children) a reference. The actual mechanisme to create the object first creates it, then does a next(x) on it to finalize it.

提交回复
热议问题