Dataclasses.asdict more flexible

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:


1 Like