Skip to content
Advertisement

Adding dataclass fields dynamically with dacite.from_dict

I am using dacite to transform a Python dictionary into a dataclass. Is there a way to dynamically add fields to a dataclass? Like in the example below, where the dataclass “Parameters” has defined only one timeseries “timeseriesA”, but there might be additional ones (provided through the dictionary) that cannot be declared.

JavaScript

In this example, “timeseriesB” will be ignored by dacite, but should be added as field for the “Parameters” dataclass.

Advertisement

Answer

In general, dynamically adding fields to a dataclass, after the class is defined, is not good practice. However, this does present a good use case for using a dict within a dataclass, due to the dynamic nature of fields in the source dict object.

Here is a straightforward example of using a dict field to handle a dynamic mapping of keys in the source object, using the dataclass-wizard which is also a similar JSON serialization library. The approach outlined below handles extraneous data in the dict object like timeseriesB for instance.

JavaScript

The dataclass-wizard admittedly doesn’t perform strict type checking like dacite, but instead performs implicit type coercion, like str to annotated int, where possible. Perhaps as a result, it’s overall much faster; the other nice thing is serialization is even slightly faster than builtin dataclasses.asdict too :-)

Here are some quick tests:

JavaScript

Results, on my PC (Windows):

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement