Why can't I override `to_dict` method of a `dataclass` object that uses `dataclasses_json`?

Bor*_*lik 2 python python-decorators python-dataclasses

dataclasses_json is a library that provides JSON capabilities to python's data classes. I noticed that overriding to_dict method has no effect. Here's an example:

@dataclass_json
@dataclass
class Message2:
    message: str
    weight: int
    def to_dict(self, encode_json=False):
        print('Custom to_dict')
        ret = {'MESSAGE': self.message, 'WEIGHT': self.weight}
        return ret
m2 = Message2('m2', 2)
print(m2.to_dict())
Run Code Online (Sandbox Code Playgroud)

The code prints the following:

{'message': 'm2', 'weight': 2}

While I was expecting

Custom to_dict
{'MESSAGE': 'm2', 'WEIGHT': 2}
Run Code Online (Sandbox Code Playgroud)

If I remove the @dataclass_json line, I get the desired output.

So, my questions are:

  1. Why defining a function had no effect with @dataclass_json but worked without it?

  2. How can I override to_dict and use @dataclass_json?

san*_*ash 7

  1. 因为只是在这里dataclass_json重写你的to_dict方法:
    cls.to_dict = DataClassJsonMixin.to_dict
Run Code Online (Sandbox Code Playgroud)
  1. 一种可能的方法是定义一个具有不同名称的方法,并在应用dataclass_json装饰器后使用此方法来创建to_dict方法。带装饰器的完整示例:
from dataclasses import dataclass
from dataclasses_json import dataclass_json


def recover_to_dict(cls):
    if hasattr(cls, '_to_dict'):
        setattr(cls, 'to_dict', getattr(cls, '_to_dict'))
    return cls


@recover_to_dict
@dataclass_json
@dataclass
class Message2:
    message: str
    weight: int
    def _to_dict(self, encode_json=False):
        print('Custom to_dict')
        ret = {'MESSAGE': self.message, 'WEIGHT': self.weight}
        return ret
m2 = Message2('m2', 2)
print(m2.to_dict())
Run Code Online (Sandbox Code Playgroud)