Hello all, so as you know dataclasses have a public function called asdict that transforms the dataclass input to a dictionary.
As an example I use this to model the response of an API and serialize this response to dict before serializing it to json.
Now, the problem happens when you want to modify how an object in the chain gets serialized to dict, currently the only way will be to create your custom asdict function. But, wouldn’t it be nice if the asdict function first checked for a to_dict method in obj and, if the method is there, calling it instead of recursively call itself? I think this approach is more flexible because it allows you to specify for any dataclass how do you want it as a dictionary.
Examples will this will be useful:
- In frameworks like https://pydantic-docs.helpmanual.io/ were you want to use dataclasses as Models and at some point they will be serialized to json for instance.