How To Do Yaml.safe_dump() And .safe_load() Of Python Object Without Yaml.yamlobject?
I want to serialize some object with yaml.safe_dump(). How can I serialize Python objects with add_representer() and add_constructor() ... I can not add yaml.YAMLObject to Thing (t
Solution 1:
You cannot construct Thing()
without handing in the name. You can solve that
in various ways, but the following should work.
def thing_constructor(self, node):
name = None
for x in node.value:
if x[0].value == 'name':
name = x[1].value
return Thing(name)
yaml.SafeLoader.add_constructor('!Thing', thing_constructor)
res = yaml.safe_load(safe_dump)
print res.name
You can simplify the setting of the name parameter, but this way it is more extensible if Thing would have taken more parameters.
Post a Comment for "How To Do Yaml.safe_dump() And .safe_load() Of Python Object Without Yaml.yamlobject?"