如何为 PyYAML 编写代表? [英] How do I write a representer for PyYAML?
问题描述
我想要一个自定义函数来序列化任意 python 对象,比如 json.dump 函数如何有一个名为default"的可选参数,如果对象不是 json 可序列化的,它应该是一个 json dumper 将调用的函数.
I want to have a custom function that serializes arbitrary python objects, like how the json.dump function has an optional arg called 'default', that should be a function that the json dumper will call if the object is not json serializable.
我只是想从 json 包中做同样的事情.
I simply want to do the equivalent of this from the json package.
json.dump(tests_dump, file('somefile', 'w+'), default = lambda x: x.__dict__)
看起来我需要从 PyYAML 文档中编写 yaml.add_representer,但确实不清楚如何执行此操作.
It looks like I need to write yaml.add_representer, from the PyYAML docs, but it really isn't clear how to do this.
推荐答案
这是 add_representer 的示例.不确定这是否正是您想要的.尽管如此...
Here is a sample for add_representer. Not sure if this is exactly what you want. Nevertheless ...
import yaml
#Arbitrary Class
class MyClass:
def __init__(self, someNumber, someString):
self.var1 = someNumber
self.var2 = someString
#define the representer, responsible for serialization
def MyClass_representer(dumper, data):
serializedData = str(data.var1) + "|" + data.var2
return dumper.represent_scalar('!MyClass', serializedData )
#'register' it
yaml.add_representer(MyClass, MyClass_representer)
obj = MyClass(100,'test')
print ( 'original Object\nvar1:{0}, var2:{1}\n'.format(obj.var1, obj.var2) )
#serialize
yamlData = yaml.dump(obj)
print('serialized as:\n{0}'.format(yamlData) )
#Now to deserialize you need a constructor
def MyClass_constructor(loader,node):
value = loader.construct_scalar(node)
someNumber,sep,someString = value.partition("|")
return MyClass(someNumber,someString)
#'register' it
yaml.add_constructor('!MyClass', MyClass_constructor)
#deserialize
obj2 = yaml.load(yamlData)
print ( 'after deserialization\nvar1:{0}, var2:{1}\n'.format(obj2.var1, obj2.var2) )
当然有代码重复,代码没有优化.您可以将这两个函数作为类的一部分,并实现 __repr__
以获得可打印的表示,您可以使用该表示来填充 MyClass_representer
中的 serializedData
Of course there is code duplication and the code is not optimized. You can make these two functions part of your Class, and also implement __repr__
to get a printable representation that you can use to populate serializedData
in MyClass_representer
这篇关于如何为 PyYAML 编写代表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!