使用 pyyaml 序列化自定义类

Tom*_*ohl 4 python pyyaml

我想通过指定如何序列化自定义类(我无法修改或猴子补丁)来序列化此类实例。

这是设置:

# some custom class which I cannot modify
class Custom:
    def __init__(self, a, b):
        self.a = a
        self.b = b

# data I want to serialize
data = [Custom(1, 2), Custom(101, 102)]
Run Code Online (Sandbox Code Playgroud)

下面是我对 JSON 的处理方式:

import json

# helper function to handle the custom class
def default(d):
    if isinstance(d, Custom):
        return dict(a=d.a, b=d.b)

print(json.dumps(data, default=default))
# expected and actual output: [{"a": 1, "b": 2}, {"a": 101, "b": 102}]
Run Code Online (Sandbox Code Playgroud)

我正在努力寻找等效的解决方案pyyaml

import yaml

def yaml_equivalent_of_default():
    "YOUR SOLUTION GOES HERE"

print(yaml.dump(data))
# expected output:
# - a: 1
#   b: 2
# - a: 101
#   b: 102
Run Code Online (Sandbox Code Playgroud)

我尝试了pyyaml 文档中提到的不同方法但无济于事。

Qui*_*Bit 5

我相信如果可以腌制自定义类成员/字段,这应该可行:

import yaml

class Custom:
    def __init__(self, a, b):
        self.a = a
        self.b = b

data_to_serialize = [Custom(1, 2), Custom(101, 102)]

def yaml_equivalent_of_default(dumper, data):
    dict_representation = data.__dict__
    node = dumper.represent_dict(dict_representation)
    return node

yaml.add_representer(Custom, yaml_equivalent_of_default)

print(yaml.dump(data_to_serialize))
Run Code Online (Sandbox Code Playgroud)

输出:

- a: 1
  b: 2
- a: 101
  b: 102
Run Code Online (Sandbox Code Playgroud)

的签名representerdef add_representer(data_type, representer, Dumper=Dumper),因此可以将 a 传递Damper给它。所有可用的自卸车都是['BaseDumper', 'SafeDumper', 'Dumper']